Python Variables
Variables are used to store data in Python programs. A variable works like a container that stores information.
Creating Variables
In Python, variables are created by assigning values using the = operator.
name = "Rahul" age = 25 salary = 50000 print(name) print(age) print(salary)
Output
Rahul 25 50000
Rules for Variable Names
- Variable names can contain letters, numbers, and underscore (_).
- Variable names cannot start with a number.
- Spaces are not allowed in variable names.
- Python keywords cannot be used as variable names.
- Variable names are case-sensitive.
Examples of Valid Variables
student_name = "Ali" marks = 90 price1 = 500 _total = 100
Examples of Invalid Variables
1name = "Ali" student name = "Ali" class = 10
Multiple Variable Assignment
Python allows assigning multiple variables in one line.
x, y, z = 10, 20, 30 print(x) print(y) print(z)
Same Value to Multiple Variables
a = b = c = 100 print(a) print(b) print(c)
Variable Data Types
Variables can store different types of data.
name = "Python" # String age = 25 # Integer price = 99.99 # Float is_active = True # Boolean
Checking Variable Type
Use type() function to check the datatype of a variable.
name = "Python" age = 25 print(type(name)) print(type(age))
Output
<class 'str'> <class 'int'>
Changing Variable Values
Variable values can be changed anytime during program execution.
city = "Delhi" print(city) city = "Mumbai" print(city)
Real Life Example
student_name = "Ali"
marks = 92
passed = True
print("Student Name:", student_name)
print("Marks:", marks)
print("Passed:", passed)