Chapter 2: Variables, Data Types and Type Conversion
2.1 Introduction
In the previous chapter, we introduced Python and learned about its basic syntax, input, output, and simple programs.
In this chapter, we will explore three important concepts:
Variables
Data types
Type conversion
These concepts form the foundation of almost every Python program.
2.2 What is a Variable?
A variable is a name that refers to a value stored or represented in a Python program.
For example:
student_name = "Rahul" age = 20 marks = 85.5
Here:
student_name refers to a text value.
age refers to a whole number.
marks refers to a decimal number.
Python allows you to create a variable simply by assigning a value to a name.
city = "Delhi"
There is no need to specify the data type separately in this basic assignment.
2.3 Assigning Values to Variables
The assignment operator = is used to assign a value.
name = "Aman" age = 22
The expression on the right side is evaluated and the resulting value is assigned to the variable on the left.
Example
x = 10 y = 20 total = x + y print(total)
Output:
30
2.4 Changing a Variable's Value
A variable can be assigned a new value during program execution.
score = 50 print(score) score = 75 print(score)
Output:
50 75
The variable score first refers to 50 and later refers to 75.
2.5 Multiple Assignment
Python allows multiple variables to be assigned in one statement.
name, age, city = "Aman", 21, "Bhopal"
This is equivalent to assigning the values individually.
You can also assign the same value to multiple variables:
x = y = z = 100
Now all three variables refer to the value 100.
2.6 Rules for Variable Names
A variable name should follow Python's naming rules.
Rules
It can contain letters.
It can contain numbers.
It can contain underscores.
It cannot begin with a number.
Spaces cannot be used.
Python keywords should not be used as variable names.
Variable names are case-sensitive.
Valid Examples
student_name = "Ravi" age2 = 25 total_marks = 450 firstName = "Aman"
Invalid Examples
2name = "Ravi" student name = "Ravi" class = 10
A descriptive variable name is generally better than a vague name.
For example:
student_marks = 85
is easier to understand than:
x = 85
2.7 Case Sensitivity
Python distinguishes between uppercase and lowercase letters.
For example:
name = "Aman" Name = "Rahul"
These are two different variable names.
Similarly:
age = 20 Age = 30
age and Age are different identifiers.
For beginners, using consistent lowercase variable names with underscores is a useful convention.
2.8 What is a Data Type?
A data type tells Python what kind of value is being represented.
For example:
age = 25
The value 25 is an integer.
Another example:
price = 99.50
The value 99.50 is a floating-point number.
Python provides several built-in data types.
Some important types are:
| Data Type | Description | Example |
|---|---|---|
| int | Whole numbers | 25 |
| float | Decimal numbers | 25.75 |
| str | Text | "Python" |
| bool | True or False | True |
| list | Ordered collection | [10, 20, 30] |
| tuple | Immutable collection | (10, 20, 30) |
| set | Collection of unique values | {10, 20, 30} |
| dict | Key-value collection | {"name": "Aman"} |
| NoneType | Represents no value | None |
We will study collections such as lists, tuples, sets, and dictionaries in greater detail in later chapters.
2.9 Integer (int)
The int type represents whole numbers without a decimal component.
Examples:
age = 25 temperature = -5 students = 40
You can perform arithmetic operations with integers.
a = 15 b = 4 print(a + b) print(a - b) print(a * b)
2.10 Floating-Point (float)
The float type represents numbers containing a decimal part.
Examples:
height = 5.8 price = 149.99 percentage = 87.5
Example:
length = 10.5 width = 4.2 area = length * width print(area)
2.11 String (str)
A string represents text.
Strings can be written using single or double quotation marks.
name = "Aman" city = 'Bhopal'
Both are valid.
You can also store numbers as strings:
number = "100"
However, "100" is text, not an integer.
This distinction becomes important when performing calculations.
2.12 Boolean (bool)
A Boolean value represents one of two logical states:
True False
Example:
is_student = True is_logged_in = False
Boolean values are commonly used in conditions and decision-making.
2.13 None
Python also has a special value called None.
It is commonly used to represent the absence of a value.
Example:
result = None print(result)
Output:
None
None is different from 0, False, and an empty string.
2.14 Finding the Data Type
The built-in type() function can be used to inspect the type of a value.
age = 25 print(type(age))
Output:
<class 'int'>
Another example:
price = 99.50 print(type(price))
Output:
<class 'float'>
And:
name = "Python" print(type(name))
Output:
<class 'str'>
2.15 Type Conversion
Sometimes a program needs to convert a value from one data type to another.
This is called type conversion or type casting.
For example, a number stored as text can sometimes be converted into an integer.
number = "50" number = int(number) print(number + 10)
Output:
60
2.16 Converting to Integer
The int() function can convert suitable values to integers.
Example:
x = int("25") print(x) print(type(x))
Output:
25 <class 'int'>
A floating-point value can also be converted to an integer:
x = int(12.8) print(x)
Output:
12
Notice that converting a floating-point number to an integer removes the fractional portion; it does not round the number to the nearest integer.
2.17 Converting to Float
The float() function can convert suitable values to floating-point numbers.
price = float("99.50") print(price)
Output:
99.5
You can also convert an integer:
number = 25 decimal_number = float(number) print(decimal_number)
Output:
25.0
2.18 Converting to String
The str() function converts a value into a string representation.
age = 25 message = "My age is " + str(age) print(message)
Output:
My age is 25
This is useful when combining text with values.
2.19 Converting to Boolean
The bool() function can be used to obtain a Boolean value.
For example:
print(bool(1)) print(bool(0))
Output:
True False
Python considers several empty values to be false-like, while many non-empty or non-zero values are true-like.
2.20 Taking Numerical Input
An important point to remember is that input() normally returns a string.
Consider:
age = input("Enter your age: ")
Even if the user enters:
25
the value received by the program is text.
If you want an integer, convert it:
age = int(input("Enter your age: "))
Similarly, for decimal input:
height = float(input("Enter your height: "))
2.21 Example: Student Marks
Let's create a small program that accepts marks and calculates their total.
maths = int(input("Enter Maths marks: ")) science = int(input("Enter Science marks: ")) english = int(input("Enter English marks: ")) total = maths + science + english print("Total marks =", total)
If the user enters:
Maths: 80 Science: 75 English: 85
The program produces:
Total marks = 240
2.22 Example: Calculate Percentage
maths = float(input("Enter Maths marks: ")) science = float(input("Enter Science marks: ")) english = float(input("Enter English marks: ")) total = maths + science + english percentage = total / 3 print("Total =", total) print("Percentage =", percentage)
This example assumes the three subjects have equal maximum marks and equal weight.
2.23 Checking Multiple Data Types
You can use type() to inspect several variables.
name = "Ravi" age = 20 percentage = 82.5 passed = True print(type(name)) print(type(age)) print(type(percentage)) print(type(passed))
This helps beginners understand how Python represents different kinds of values.
2.24 Dynamic Typing in Python
Python is dynamically typed.
This means a variable does not need a fixed type declaration in the way some statically typed languages require.
For example:
value = 100 print(type(value)) value = "Python" print(type(value))
The same variable name can later refer to a value of another type.
Output:
<class 'int'> <class 'str'>
Although this is allowed, clear and consistent variable usage generally makes programs easier to understand.
2.25 Common Type Conversion Errors
Not every value can be converted successfully.
For example:
age = int("hello")
This will produce an error because "hello" does not represent a valid integer.
Similarly:
number = float("Python")
cannot produce a floating-point number from that text.
Therefore, programs that accept user input should consider the possibility of invalid input.
Error handling will be discussed in a later chapter.
2.26 Mini Project: Simple Bill Calculator
Let's create a small bill calculator.
item_price = float(input("Enter item price: ")) quantity = int(input("Enter quantity: ")) total = item_price * quantity print("Total amount =", total)
Example
If the price is 120.50 and quantity is 3:
Total amount = 361.5
This simple program demonstrates:
Variables
float
int
User input
Multiplication
Output
Chapter 2 Summary
In this chapter, you learned:
What variables are
How to assign values
Multiple assignment
Variable naming rules
Case sensitivity
Python's basic data types
int
float
str
bool
None
The type() function
Type conversion
int()
float()
str()
bool()
Numerical input
Dynamic typing
Common conversion errors
Quick Revision Questions
1. What is a variable?
A variable is a name used to refer to a value in a Python program.
2. Which symbol is used for assignment?
The = operator.
3. Which data type stores whole numbers?
int.
4. Which data type stores decimal numbers?
float.
5. Which data type is used for text?
str.
6. Which data type represents True and False?
bool.
7. Which function tells you the type of a value?
type().
8. Which function converts suitable text or values to an integer?
int().
9. Which function converts a value to a floating-point number?
float().
10. What type does input() normally return?
str (string).
Practice Exercises
Exercise 1
Create a program that asks for a user's name and age and displays both.
Exercise 2
Create a program that accepts two numbers and displays:
Sum
Difference
Product
Division
Exercise 3
Create a program that accepts the price of an item and quantity, then calculates the total cost.
Exercise 4
Create a program that accepts marks in five subjects and calculates the total and average.
Exercise 5
Create a program that accepts a temperature in Celsius and converts it into Fahrenheit.
Formula:
Fahrenheit = (Celsius × 9/5) + 32
Chapter 2 Activity
Create a Student Information Program that asks for:
Student name
Age
Class
Three subject marks
Then display the student's information, total marks, and average marks.
Next Chapter: Python Operators and Expressions