A variable is a name that refers to a value. Create one by assigning with = — no keyword or type is needed.
city = "Patna"
Dynamic typing
Python decides the type from the value, and a variable can later hold a different type. Use type(x) to check.
Naming rules
- Letters, digits and underscores only
- Cannot start with a digit
- Cannot be a keyword (
if,for,class, ...) - Case sensitive
Naming style
- Variables and functions:
snake_case→total_marks - Constants:
UPPER_CASE→MAX_USERS = 100(Python does not enforce constants; it is a convention) - Classes:
PascalCase
Handy tricks
- Multiple assignment:
x, y, z = 1, 2, 3 - Same value:
a = b = 0 - Swap:
a, b = b, a - Delete:
del x
Choose clear names: price is better than p.
Example
Example — Variables in action
Python
name = "Ravi"
age = 25
height = 5.8
is_student = True
print(type(name), type(age), type(height), type(is_student))
# Multiple assignment and swapping
x, y = 10, 20
x, y = y, x
print("x =", x, "y =", y)
# Dynamic typing
value = 100
value = "one hundred"
print(value, type(value))
GST_RATE = 0.18 # constant by convention
print("Tax on 500:", 500 * GST_RATE)
Output: <class 'str'> <class 'int'> <class 'float'> <class 'bool'>, x = 20 y = 10, one hundred <class 'str'>, Tax on 500: 90.0