Python Variables
A variable is a name that refers to a value, so you can use the value later, change it, and make your code readable. In Python you create a variable simply by assigning to it.
- Create and update variables
- Follow Python’s naming rules
- Assign several variables at once
- Understand that names point to objects
Create a variable
Write a name, an equals sign and a value. Python creates the variable the first time you assign to it. There is no var, let or type declaration.
browser = "chromium"timeout = 30headless = True print(browser, timeout, headless)chromium 30 True
= means assign, not “is equal to”. timeout = 30 stores 30 under the name timeout. To compare two values you use ==, covered in Operators.
Change a variable
Assigning again replaces the old value. The new value can even be a different type, because Python variables do not have a fixed type; the value does.
count = 1count = count + 1 # read the old value, add 1, store the resultcount += 1 # the same thing, written shorterprint(count) count = "three" # now it holds a stringprint(count, type(count))3 three <class 'str'>
Naming rules
| Rule | Valid | Invalid |
|---|---|---|
| Letters, digits and underscores only | user_2 | user-2, user 2 |
| Cannot start with a digit | _2nd, second | 2nd |
| Cannot be a keyword | class_name | class, for |
| Case-sensitive | total and Total are different |
user-name = "asha" File "main.py", line 1
user-name = "asha"
^^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?Naming conventions
These are not enforced by Python but every Python developer follows them (they come from the PEP 8 style guide):
snake_casefor variables and functions:max_retries,page_title.UPPER_CASEfor constants that should not change:BASE_URL,MAX_RETRIES.PascalCasefor classes:LoginPage.- Use names that say what the value means:
retriesbeatsr,price_in_rupeesbeatsp.
Assign several variables at once
x, y, z = 10, 20, 30 # one value per nameprint(x, y, z) a = b = c = 0 # the same value to every nameprint(a, b, c) first, *rest = [1, 2, 3, 4] # * collects the leftovers into a listprint(first, rest)10 20 30 0 0 0 1 [2, 3, 4]
The number of names on the left must match the number of values, unless one name has *:
x, y = 1, 2, 3Traceback (most recent call last):
File "main.py", line 1, in <module>
x, y = 1, 2, 3
^^^^
ValueError: too many values to unpack (expected 2, got 3)Swap two variables
Many languages need a temporary variable to swap. Python swaps in one line:
a = 10b = 20a, b = b, aprint("a =", a, "b =", b)a = 20 b = 10
Variables are names for objects
A variable does not contain the value; it refers to an object in memory. Two names can refer to the same object. id() shows an object’s identity and is checks whether two names refer to the same object.
scores = [90, 85]backup = scores # a second name for the same listbackup.append(70) print(scores)print(backup is scores)[90, 85, 70] True
This is why changing a list through one name shows up through the other. Numbers and strings cannot be changed in place, so for them this never surprises you:
a = 5b = ab = b + 1 # creates a new int object; a still refers to 5print(a, b)5 6
The Lists lesson shows how to make a real copy with .copy() when you need one.
Delete a variable
del removes a name. Using the name afterwards raises NameError.
temp = 42del tempprint(temp)Traceback (most recent call last):
File "main.py", line 3, in <module>
print(temp)
^^^^
NameError: name 'temp' is not definedConstants
Python has no true constants. By convention a name in UPPER_CASE tells other developers “do not change this”:
BASE_URL = "https://sqatools.in"MAX_RETRIES = 3 for attempt in range(1, MAX_RETRIES + 1): print(f"Attempt {attempt} of {MAX_RETRIES} on {BASE_URL}")Attempt 1 of 3 on https://sqatools.in Attempt 2 of 3 on https://sqatools.in Attempt 3 of 3 on https://sqatools.in
Check your understanding
Predict the output
a = 3b = aa = a * 2print(a, b)6 3
b = a makes b refer to the int 3. a * 2 creates a new object 6 and rebinds only a, so b is still 3.
Quick quiz
1. Which is a valid Python variable name?
Only letters, digits and underscores are allowed, and a name cannot start with a digit.
2. What does x, y = y, x do?
The right side is built first as a tuple (y, x), then unpacked into x and y.
3. What is the convention for a value that should never change?
PEP 8 uses upper case with underscores for constants, such as MAX_RETRIES.
4. What does first, *rest = [5, 6, 7] put in rest?
A starred name collects the remaining items into a list.
Exercise: shopping cart total
Store the item price, quantity and discount percentage in well-named variables, then print the final amount.
price = 250, quantity = 4, discount = 10%
Subtotal: 1000 Final amount: 900.0
Hint 1
The discount amount is subtotal * discount_percent / 100.
price = 250quantity = 4discount_percent = 10 subtotal = price * quantityfinal_amount = subtotal - subtotal * discount_percent / 100print("Subtotal:", subtotal)print("Final amount:", final_amount)Subtotal: 1000 Final amount: 900.0
Each value gets a name that says what it means, so the formula reads like the problem. Division with / always gives a float, which is why the final amount prints as 900.0.
Program Practice
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python variables FAQ
Do I need to declare a variable type in Python?
No. Python works out the type from the value you assign. n = 5 is an int and n = "5" is a str. You can add optional type hints, such as n: int = 5, for readability.
How do I swap two variables in Python?
Use tuple unpacking: a, b = b, a. No temporary variable is needed.
What is the difference between = and ==?
= assigns a value to a name. == compares two values and returns True or False.
Can a variable name start with an underscore?
Yes. A single leading underscore, as in _cache, is a convention meaning “internal, do not use from outside”.