Python Tutorial menu

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

python
student = "Ali"
age = 19
fee_paid = True
print(student)
print(age)
print(fee_paid)
Output
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

python
balance = 500
print(balance)
balance = 750
print(balance)
Output
500
750

A variable can even change its type. It can hold a number first and text later. Python does not complain.

Naming Rules

RuleAllowedNot allowed
Start with a letter or underscorename, _count2name
Only letters, digits and underscorestotal_billtotal-bill, total bill
Case sensitiveage and Age are different
Not a Python keywordmy_classclass, 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

python
x, y, z = 10, 20, 30
print(x, y, z)

a = b = c = "Karachi"
print(a, b, c)
Output
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

python
item = "Shirt"
price = 1800
print("The", item, "costs Rs", price)
Output
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

python
item = "Shirt"
price = 1800
print(f"The {item} costs Rs {price}")
Output
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

python
first = "tea"
second = "coffee"
first, second = second, first
print(first, second)
Output
coffee tea

Exercise

Exercise

Which of these is a valid Python variable name?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp