Python Variables
A variable is a name that stores a value, so you can use it again later.
Creating Variables
In Python you create a variable the moment you give it a value with =. There is no special keyword.
Example
student = "Ali"
age = 19
fee_paid = True
print(student)
print(age)
print(fee_paid)Ali 19 True
Think of a variable as a labelled box. The label is the name (student) and the thing inside is the value ("Ali").
Changing a Value
A variable can get a new value at any time. The old value is replaced.
Example
balance = 500
print(balance)
balance = 750
print(balance)500 750
A variable can even change its type. It can hold a number first and text later. Python does not complain.
Naming Rules
| Rule | Allowed | Not allowed |
|---|---|---|
| Start with a letter or underscore | name, _count | 2name |
| Only letters, digits and underscores | total_bill | total-bill, total bill |
| Case sensitive | age and Age are different | |
| Not a Python keyword | my_class | class, if, for |
Python programmers usually write variable names in lowercase with underscores between words, like monthly_salary. This style is called snake_case.
Many Values in One Line
You can give values to several variables in one line:
Example
x, y, z = 10, 20, 30
print(x, y, z)
a = b = c = "Karachi"
print(a, b, c)10 20 30 Karachi Karachi Karachi
The number of names on the left must match the number of values on the right in the first form.
Printing Variables With Text
Separate items with commas in print(). Python adds a space between them:
Example
item = "Shirt"
price = 1800
print("The", item, "costs Rs", price)The Shirt costs Rs 1800
A cleaner way is an f-string. Put f before the quotes and write variable names inside curly brackets {}:
Example
item = "Shirt"
price = 1800
print(f"The {item} costs Rs {price}")The Shirt costs Rs 1800
You will use f-strings a lot. They are covered more in the Strings lesson.
Swapping Two Variables
Python has a short trick to swap values:
Example
first = "tea"
second = "coffee"
first, second = second, first
print(first, second)coffee tea
Exercise
Exercise
Which of these is a valid Python variable name?
