Python Variables
In Python, a variable is a named reference to a value stored in memory. Unlike statically typed languages, Python creates a variable the moment you assign a value to it using the = operator—no separate type declaration is needed.
Creating Variables in Python
Assign values such as text (strings) or numbers directly to variable names:
student_name = "Aarav"
course_fee = 4999
is_enrolled = True
print(student_name)
print(course_fee)
print(is_enrolled)
Variables in Python are dynamically typed, meaning a variable can hold one type of value and later be reassigned a value of a different type:
value = 100 # Initially an integer
value = "One Hundred" # Now a string
print(value)
Python Variable Naming Rules
- Allowed Characters: Names can contain letters (
a-z,A-Z), digits (0-9), and underscores (_). - Cannot Start with a Digit: A variable name must start with a letter or an underscore (
_), never a number (for example,1st_nameis invalid). - No Spaces or Special Symbols: Spaces, hyphens (
-), and symbols like@or$are not allowed. Usesnake_casesuch asuser_age. - Case-Sensitive & No Keywords:
ageandAgeare different variables, and you cannot use reserved Python keywords likeif,for, orclassas variable names.
Assigning Multiple Values
Python lets you assign multiple variables on a single line or give the same value to several variables at once:
x, y, z = "Apple", "Banana", "Cherry"
print(x, y, z)
a = b = c = 50
print(a, b, c)
Checking Variable Type with type()
You can inspect the data type of any variable using the built-in type() function:
rating = 4.8
topic = "Variables"
print(type(rating)) # <class 'float'>
print(type(topic)) # <class 'str'>
total_price instead of short unclear names so your code is easier to read and maintain.