Python Variables and Data Types
Variables and data types are fundamental concepts in Python programming. Almost every Python program uses variables to store, process, and manipulate information.
In this lesson, you will learn how Python variables work, how dynamic typing works, Python's built-in numeric and text types, type checking, type conversion, user input, output formatting, multiple assignment, and variable swapping.
By the end of this lesson, you will be able to create variables, identify Python data types, convert values between types, accept input from users, and format program output effectively.
What Is a Variable in Python?
A variable is a name that refers to an object containing a value.
A simple way to visualize a variable is:
1Variable Name ─────► Object / Value 2 age ─────► 20
In Python, you create a variable by assigning a value to a name using the = operator.
Syntax
1variable_name = value
Basic Example
1name = "Ankit" 2age = 22 3city = "Delhi" 4 5print(name) 6print(age) 7print(city)
Output:
1Ankit 222 3Delhi
Python does not require you to specify the variable's type when assigning a value.
1name = "Ankit" 2age = 22
Python determines the type of each value at runtime.
Understanding Variable Assignment
It is useful to understand that Python variables are names bound to objects, rather than traditional boxes that directly contain values.
For example:
1age = 22
Conceptually:
1age ─────► 22
The name age refers to an integer object whose value is 22.
If you later write:
1age = 30
the name age is now bound to another integer object:
1age ─────► 30
This model becomes particularly important when working with mutable objects such as lists and dictionaries.
Variable Naming Rules
Python has specific rules for naming variables.
Valid Variable Names
1name = "Ankit" 2_age = 22 3student_name = "Rahul" 4student2 = "Aman" 5total_marks = 450
Invalid Variable Names
12name = "Ankit" # Cannot start with a number 2my-name = "Python" # Hyphen is not allowed 3class = "Python" # Reserved keyword
A Python identifier can contain:
- Letters (
a-z,A-Z) - Numbers (
0-9) - Underscores (
_)
However, it cannot begin with a number.
Python identifiers are also case-sensitive.
1name = "Alice" 2Name = "Bob" 3 4print(name) 5print(Name)
Output:
1Alice 2Bob
name and Name are different identifiers.
Python Variable Naming Best Practices
Use descriptive names that communicate what the value represents.
Good:
1student_name = "Ankit" 2total_marks = 450 3user_age = 22 4is_logged_in = True
Less descriptive:
1x = "Ankit" 2a = 450 3b = 22
For variables and functions, Python commonly follows the snake_case naming convention.
1first_name = "Alice" 2last_name = "Smith" 3total_price = 999.99
Good variable names make programs easier to read, debug, and maintain.
Dynamic Typing in Python
Python is a dynamically typed language.
This means you do not normally need to declare the type of a variable before assigning a value.
For example, in Java you might write:
1int age = 20;
In Python, you simply write:
1age = 20
Python determines that age refers to an integer object.
Changing the Type of a Variable
A Python name can later be rebound to an object of a different type.
1x = 10 2 3print(x) 4 5x = "Python" 6 7print(x)
Output:
110 2Python
The name x first refers to an integer and later refers to a string.
You can inspect the current type with type():
1data = 100 2print(type(data)) 3 4data = 12.5 5print(type(data)) 6 7data = True 8print(type(data))
Output:
1<class 'int'> 2<class 'float'> 3<class 'bool'>
Dynamic typing makes Python concise, but you still need to understand what type of object your code is working with.
Python Constants
Python does not provide a dedicated const keyword for creating immutable constants.
Instead, Python developers use a naming convention: constant names are normally written in uppercase.
1PI = 3.14159 2MAX_USERS = 100 3SITE_NAME = "Tech3Space" 4 5print(PI) 6print(MAX_USERS) 7print(SITE_NAME)
Output:
13.14159 2100 3Tech3Space
Uppercase names communicate that a value is intended to remain unchanged.
However, Python does not prevent reassignment:
1PI = 3.14 2 3PI = 5 4 5print(PI)
Output:
15
Therefore, uppercase names represent a convention rather than a language-enforced constant.
Python Variable References
Python variables are references to objects.
Consider:
1a = 10 2b = a 3 4print(a) 5print(b)
Output:
110 210
Both names currently refer to an integer object representing 10.
If you reassign a:
1a = 20 2 3print(a) 4print(b)
Output:
120 210
Reassigning a does not change what b refers to.
Mutable Objects and Shared References
The behavior becomes more important with mutable objects such as lists.
1list1 = [10, 20] 2list2 = list1 3 4list2.append(30) 5 6print(list1) 7print(list2)
Output:
1[10, 20, 30] 2[10, 20, 30]
Why did both lists change?
Because:
1list2 = list1
does not create a new list. Both names refer to the same list object.
Conceptually:
1list1 ──┐ 2 ├──► [10, 20, 30] 3list2 ──┘
If you want an independent list, you can create a copy:
1list1 = [10, 20] 2list2 = list1.copy() 3 4list2.append(30) 5 6print(list1) 7print(list2)
Output:
1[10, 20] 2[10, 20, 30]
This distinction between assignment, references, and copying becomes increasingly important as you work with Python collections.
Using the id() Function
The built-in id() function returns an integer that identifies an object during its lifetime.
Example:
1a = 100 2b = a 3 4print(id(a)) 5print(id(b))
In this example, both names refer to the same object, so they will normally have the same id() value.
Do not rely on id() as a permanent physical memory address. It is better understood as an identity value for the object within that Python process.
Python Numeric Data Types
Python provides three built-in numeric types:
int— integersfloat— floating-point numberscomplex— complex numbers
Example:
1integer_number = 100 2decimal_number = 25.5 3complex_number = 3 + 4j 4 5print(integer_number) 6print(decimal_number) 7print(complex_number)
Output:
1100 225.5 3(3+4j)
Python Integer Type
An int represents whole numbers without a decimal point.
Examples:
110 2-5 31000 40
Example:
1marks = 95 2 3print(marks) 4print(type(marks))
Output:
195 2<class 'int'>
Python integers can represent arbitrarily large integers, limited primarily by available memory.
1large_number = 10 ** 100 2 3print(large_number)
Python handles this without requiring a separate "long integer" type.
Integer Arithmetic
Python supports common arithmetic operations.
1a = 15 2b = 4 3 4print(a + b) # Addition 5print(a - b) # Subtraction 6print(a * b) # Multiplication 7print(a // b) # Floor division 8print(a % b) # Remainder 9print(a ** b) # Exponentiation
Output:
119 211 360 43 53 650625
The // operator performs floor division, while % returns the remainder.
For positive numbers:
1print(15 // 4) 2print(15 % 4)
Output:
13 23
Python Float Type
A float represents a floating-point number.
Examples:
13.14 212.75 30.5 4-8.25
Example:
1price = 99.99 2 3print(price) 4print(type(price))
Output:
199.99 2<class 'float'>
You can perform arithmetic operations with floating-point values.
1x = 5.5 2y = 2.5 3 4print(x + y) 5print(x * y) 6print(x / y)
Output:
18.0 213.75 32.2
Keep in mind that floating-point numbers can have small representation errors because many decimal fractions cannot be represented exactly in binary floating-point.
For applications such as financial calculations where exact decimal arithmetic is important, Python's decimal module may be more appropriate.
Python Complex Numbers
Python supports complex numbers using the j suffix for the imaginary component.
The general form is:
1a + bj
Example:
1z = 2 + 5j 2 3print(z) 4print(type(z))
Output:
1(2+5j) 2<class 'complex'>
You can access the real and imaginary components:
1z = 3 + 8j 2 3print(z.real) 4print(z.imag)
Output:
13.0 28.0
Complex numbers are useful in areas such as engineering, scientific computing, signal processing, and mathematics.
Python Boolean Type
The Boolean type, bool, has two values:
1True 2False
Example:
1is_student = True 2is_admin = False 3 4print(is_student) 5print(is_admin)
Output:
1True 2False
Booleans are frequently used in conditions.
1age = 20 2 3print(age >= 18) 4print(age < 18)
Output:
1True 2False
Comparison operators return Boolean values.
Python Strings
A string is a sequence of characters used to represent text.
Example:
1name = "Python" 2 3print(name) 4print(type(name))
Output:
1Python 2<class 'str'>
Python strings can be written using single or double quotes.
Single Quotes
1language = 'Python'
Double Quotes
1language = "Python"
Both create a string.
Multiline Strings
Triple-quoted strings can contain multiple lines.
1text = """Python 2is 3awesome""" 4 5print(text)
Output:
1Python 2is 3awesome
Triple-quoted strings are also commonly used for docstrings.
Accessing String Characters
Python strings are indexed starting from 0.
1word = "Python" 2 3print(word[0]) 4print(word[2]) 5print(word[-1])
Output:
1P 2t 3n
The indexes are:
1 P y t h o n 2 0 1 2 3 4 5
Negative indexes start from the end:
1 P y t h o n 2-6 -5 -4 -3 -2 -1
String Length
Use the built-in len() function to determine the number of characters in a string.
1name = "Programming" 2 3print(len(name))
Output:
111
Spaces are also counted as characters.
1text = "Hello World" 2 3print(len(text))
Output:
111
String Concatenation
You can combine strings using the + operator.
1first = "Hello" 2second = "World" 3 4message = first + " " + second 5 6print(message)
Output:
1Hello World
String Repetition
The * operator can repeat a string.
1print("Python " * 3)
Output:
1Python Python Python
Python None
None is a special Python object that represents the absence of a value.
Example:
1data = None 2 3print(data) 4print(type(data))
Output:
1None 2<class 'NoneType'>
None is commonly used when a value is currently unavailable or when a function intentionally returns no meaningful value.
Example:
1result = None 2 3if result is None: 4 print("No result found")
Output:
1No result found
Use is None rather than == None when checking for None.
Type Checking with type()
The type() function tells you the type of an object.
1x = 100 2y = "Python" 3z = 5.6 4 5print(type(x)) 6print(type(y)) 7print(type(z))
Output:
1<class 'int'> 2<class 'str'> 3<class 'float'>
type() is particularly useful while learning Python and debugging code.
Type Checking with isinstance()
The isinstance() function checks whether an object is an instance of a particular type.
1age = 20 2 3print(isinstance(age, int)) 4print(isinstance(age, float))
Output:
1True 2False
You can also check multiple types:
1value = 10 2 3print(isinstance(value, (int, float)))
Output:
1True
For many programs, isinstance() is preferable when you need to test whether a value belongs to a particular type.
Type Conversion in Python
Type conversion, also called type casting, means converting a value from one type to another.
Python provides built-in functions such as:
1int() 2float() 3str() 4bool()
Convert Integer to Float
1num = 10 2 3result = float(num) 4 5print(result) 6print(type(result))
Output:
110.0 2<class 'float'>
Convert Float to Integer
1price = 99.99 2 3result = int(price) 4 5print(result)
Output:
199
Be careful: int() truncates the fractional part. It does not round the value.
1print(int(9.99)) 2print(int(-9.99))
Output:
19 2-9
Convert Integer to String
1age = 22 2 3age_text = str(age) 4 5print(age_text) 6print(type(age_text))
Output:
122 2<class 'str'>
This is useful when you need to combine numbers with text.
Convert String to Integer
If a string contains a valid integer representation, you can convert it using int().
1num = "150" 2 3number = int(num) 4 5print(number) 6print(type(number))
Output:
1150 2<class 'int'>
An invalid conversion raises an exception:
1num = "hello" 2 3number = int(num)
This results in a ValueError.
Convert String to Float
1price = "49.99" 2 3number = float(price) 4 5print(number) 6print(type(number))
Output:
149.99 2<class 'float'>
Boolean Conversion
The bool() function converts a value to a Boolean.
1print(bool(1)) 2print(bool(0)) 3print(bool("")) 4print(bool("Python"))
Output:
1True 2False 3False 4True
Some values are considered falsey, including:
1False 2None 30 40.0 5"" 6[] 7{} 8set()
Most other objects are truthy.
This concept becomes important when writing conditions.
Taking User Input with input()
The input() function allows a Python program to receive text from the user.
Example:
1name = input("Enter your name: ") 2 3print("Hello", name)
If the user enters:
1Ankit
the program displays:
1Hello Ankit
Important: input() Returns a String
Regardless of what the user enters, input() returns a string.
1age = input("Enter your age: ") 2 3print(type(age))
Example output:
1<class 'str'>
If you need a number, explicitly convert the input.
1age = int(input("Enter your age: ")) 2 3print(age + 5)
If the user enters:
122
the output is:
127
If the user enters something that cannot be converted to an integer, Python raises a ValueError.
Building a Simple Calculator
You can combine input(), float(), variables, and arithmetic operators to create a basic calculator.
1num1 = float(input("Enter first number: ")) 2num2 = float(input("Enter second number: ")) 3 4sum_result = num1 + num2 5 6print(f"Sum = {sum_result}")
Example:
1Enter first number: 10 2Enter second number: 5 3Sum = 15.0
Later in the course, you can improve this calculator by adding subtraction, multiplication, division, error handling, and a menu system.
Output Formatting in Python
Python provides several ways to format output.
Using Commas with print()
1name = "Ankit" 2age = 22 3 4print("Name:", name) 5print("Age:", age)
Output:
1Name: Ankit 2Age: 22
Using format()
Python's str.format() method can insert values into a string.
1name = "Ankit" 2age = 22 3 4print("My name is {} and I am {} years old.".format(name, age))
Output:
1My name is Ankit and I am 22 years old.
Using f-Strings
For modern Python code, f-strings are usually the clearest choice.
1name = "Ankit" 2age = 22 3 4print(f"My name is {name} and I am {age} years old.")
Output:
1My name is Ankit and I am 22 years old.
You can also evaluate expressions inside an f-string:
1price = 100 2quantity = 3 3 4print(f"Total = {price * quantity}")
Output:
1Total = 300
Formatting Decimal Numbers
You can control the number of decimal places with an f-string.
1pi = 3.14159265 2 3print(f"{pi:.2f}")
Output:
13.14
Another example:
1price = 1499.5678 2 3print(f"Price: ₹{price:.2f}")
Output:
1Price: ₹1499.57
Multiple Assignment
Python allows you to assign multiple values in a single statement.
1a, b, c = 10, 20, 30 2 3print(a) 4print(b) 5print(c)
Output:
110 220 330
This is called multiple assignment or iterable unpacking, depending on the context.
Assigning the Same Value
You can assign the same value to multiple names:
1x = y = z = 100 2 3print(x) 4print(y) 5print(z)
Output:
1100 2100 3100
Each name refers to the same integer object in this example.
Swapping Variables in Python
Python provides a simple and elegant way to swap two variables.
Pythonic Approach
1a = 10 2b = 20 3 4a, b = b, a 5 6print(a) 7print(b)
Output:
120 210
This is the preferred approach in normal Python code.
Using a Temporary Variable
The traditional approach uses a temporary variable.
1a = 10 2b = 20 3 4temp = a 5a = b 6b = temp 7 8print(a) 9print(b)
Output:
120 210
Arithmetic Swap
You may also encounter an arithmetic approach:
1a = 10 2b = 20 3 4a = a + b 5b = a - b 6a = a - b 7 8print(a) 9print(b)
Output:
120 210
Although this works for suitable numeric values, it is generally less readable than Python's multiple-assignment syntax. Prefer:
1a, b = b, a
in normal Python programs.
Practical Project: Student Information Program
Let's combine variables, strings, integers, Boolean values, input, and f-strings.
1name = input("Enter your name: ") 2age = int(input("Enter your age: ")) 3city = input("Enter your city: ") 4course = input("Enter your course: ") 5 6is_student = True 7 8print("\nStudent Information") 9print("-------------------") 10print(f"Name: {name}") 11print(f"Age: {age}") 12print(f"City: {city}") 13print(f"Course: {course}") 14print(f"Student: {is_student}")
Example:
1Enter your name: Ankit 2Enter your age: 22 3Enter your city: Delhi 4Enter your course: Python 5 6Student Information 7------------------- 8Name: Ankit 9Age: 22 10City: Delhi 11Course: Python 12Student: True
This example combines several concepts from this lesson into one practical program.
Common Beginner Mistakes
Mistake 1: Starting a Variable With a Number
Incorrect:
12name = "Ankit"
Correct:
1name2 = "Ankit"
Mistake 2: Using a Hyphen
Incorrect:
1student-name = "Ankit"
Correct:
1student_name = "Ankit"
Mistake 3: Using a Keyword
Incorrect:
1class = "Python"
Correct:
1class_name = "Python"
Mistake 4: Forgetting That input() Returns a String
Incorrect:
1age = input("Enter age: ") 2 3print(age + 5)
Correct:
1age = int(input("Enter age: ")) 2 3print(age + 5)
Mistake 5: Expecting int() to Round a Number
1print(int(9.99))
Output:
19
int() removes the fractional part; it does not round to the nearest integer.
Module Summary
In this lesson, you learned how Python variables and data types work.
You learned:
- What Python variables are
- Variable assignment
- Variable naming rules
- Naming conventions
- Dynamic typing
- Python constants
- Object references
- Mutable objects
- The
id()function - Numeric data types
- Integers
- Floating-point numbers
- Complex numbers
- Boolean values
- Strings
- String indexing
- String length
- String concatenation
- String repetition
Nonetype()isinstance()- Type conversion
int()float()str()bool()input()- Output formatting
- f-strings
- Multiple assignment
- Variable swapping
These concepts are essential for understanding more advanced Python topics such as operators, conditional statements, loops, functions, collections, and object-oriented programming.
Practice Exercises
Exercise 1: Personal Information
Create variables for:
- Name
- Age
- City
- Programming language
Print all values.
Exercise 2: Data Types
Create one variable for each of these types:
1int 2float 3complex 4bool 5str 6NoneType
Use type() to display their types.
Exercise 3: Type Conversion
Convert:
1integer → float 2float → integer 3integer → string 4string → integer 5string → float
Print both the converted value and its type.
Exercise 4: User Input
Ask the user for:
- Name
- Age
- City
Display the information using an f-string.
Exercise 5: Calculator
Ask the user for two numbers and display:
- Sum
- Difference
- Product
- Division
- Remainder
Exercise 6: Variable Swap
Create two variables and swap their values using:
1a, b = b, a
Exercise 7: String Operations
Create a string and demonstrate:
- Indexing
len()- Concatenation
- Repetition
Exercise 8: Student Profile
Build a small student profile application that accepts user input and displays a formatted profile.
Quiz
Question 1
Which symbol is used for assignment in Python?
A. ==
B. =
C. =>
D. :=
Answer: B. =
Question 2
Which data type represents whole numbers?
A. float
B. str
C. int
D. bool
Answer: C. int
Question 3
What does input() return?
A. Always an integer B. Always a float C. A string D. A Boolean
Answer: C. A string
Question 4
Which is a valid Python variable?
A. 2name
B. student-name
C. student_name
D. class
Answer: C. student_name
Question 5
What is the type of 3.14?
A. int
B. float
C. complex
D. str
Answer: B. float
Question 6
What does None represent?
A. Zero B. False C. An empty string D. Absence of a value
Answer: D. Absence of a value
Question 7
What is the recommended Pythonic way to swap two variables?
1a, b = b, a
Question 8
Which function checks whether an object is an instance of a particular type?
1isinstance()
What's Next?
In the next lesson, you will learn about Python Operators.
You will explore:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
- Operator precedence
- Practical expressions and examples