A variable is a named location in memory used to store data. Think of it as a labelled container that holds a value. In Python, a variable is created the moment you first assign a value to it — no separate declaration is needed.
name = "Ali" # string variable
age = 17 # integer variable
gpa = 3.85 # float variable
=The = symbol is the assignment operator. It takes the value on the right-hand side and stores it in the variable on the left-hand side.
x = 10 # assigns integer 10 to x
y = x + 5 # evaluates x+5 (=15) and assigns to y
Note: = (assignment) is different from == (equality comparison).
A variable name is also called an identifier. The following rules apply:
| Rule | Valid Example | Invalid Example |
|---|---|---|
Must start with a letter or _ | _score, total | 2score |
Can contain letters, digits, _ | my_var2 | my-var |
| Cannot be a Python keyword | value | if, for |
| Case-sensitive | Age ≠ age | — |
| No spaces allowed | first_name | first name |
# Valid names
student_name = "Sara"
_count = 0
totalMarks2 = 95
# Invalid names (will cause SyntaxError)
# 2fast = True
# my-var = 10
# class = "A" (keyword)
Python is a dynamically typed language. This means:
x = 5 # x is an int
print(type(x)) # <class 'int'>
x = "Hello" # x is now a str
print(type(x)) # <class 'str'>
x = 3.14 # x is now a float
print(type(x)) # <class 'float'>
Python allows assigning values to multiple variables in a single line:
# Assign different values
a, b, c = 1, 2, 3
# Assign the same value to multiple variables
x = y = z = 0
Use the built-in type() function to check what data type a variable currently holds:
marks = 85
print(type(marks)) # <class 'int'>
price = 99.9
print(type(price)) # <class 'float'>
Variable-related bugs are among the most common in Python programs:
| Error Type | Example | Cause |
|---|---|---|
NameError | print(scroe) | Variable name misspelled or not yet assigned |
TypeError | "Age: " + 17 | Mixing incompatible types |
SyntaxError | 2x = 5 | Invalid variable name |
To debug these, read the error message carefully — Python tells you the line number and type of error.
# NameError example
# print(scroe) # NameError: name 'scroe' is not defined
score = 90
print(score) # Correct