Chapter 3 - Variables and Data Types

By Ankit Sir • DevTeam

Chapter 3

Variables and Data Types

In this chapter, we will learn about variables, different data types in Python, rules for naming variables, operators, type conversion, and taking input from the user. This chapter builds the foundation for writing meaningful Python programs.

Variables

Variables in Python

A variable is a name given to a memory location. It is used to store data values so that they can be reused later. Python automatically identifies the data type of a variable.

a = 71        # a is an integer
b = 88.44     # b is a float
name = "Harry"  # name is a string
    
Data Types

Data Types in Python

  • Integer (int) – Whole numbers (Example: 10, -5, 71)
  • Floating Point (float) – Decimal numbers (Example: 3.14, 88.44)
  • String (str) – Sequence of characters written inside quotes
  • Boolean (bool) – Stores True or False
  • None (NoneType) – Represents absence of value
Concept

Automatic Type Identification

Python is a dynamically typed language. There is no need to declare the data type explicitly. Python automatically identifies the type of data stored in a variable.

a = 31
type(a)     # <class 'int'>

b = "31"
type(b)     # <class 'str'>
    
Rules

Rules for Defining a Variable Name

  • Variable names can contain alphabets, digits, and underscore (_)
  • Must start with an alphabet or underscore
  • Cannot start with a digit
  • No whitespace allowed inside variable names

Valid Variable Names: Ankit, one8, seven, _seven

Invalid Variable Names: 8one ❌, my name ❌, @value ❌

Operators

Operators in Python

  • Arithmetic Operators: +, -, *, /
  • Assignment Operators: =, +=, -=, *=
  • Comparison Operators: ==, >, <, >=, <=, !=
  • Logical Operators: and, or, not
Function

type() Function

The type() function is used to find the data type of a variable.

x = 10
type(x)   # <class 'int'>
    
Conversion

Typecasting in Python

Typecasting means converting one data type into another. Python provides built-in functions for type conversion.

str(31)      # "31"
int("32")    # 32
float(32)    # 32.0
    

Note: "31" is a string literal, while 31 is a numeric literal.

Input

input() Function

The input() function is used to take input from the user. Input is always taken as a string by default.

a = input("Enter number: ")
    

If user enters 34 → variable stores "34" (string)

Examples

Integer and Float Input Examples

a = int(input("Enter your age: "))
print(a + 5)
    
b = float(input("Enter price: "))
print(b * 1.18)
    
Practice

Adding Two Numbers

x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Sum is:", x + y)
    

If user enters 12 and 8 → Output: Sum is: 20