Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Variables

A variable is a name for a value. You create a variable by giving it a value with the equals sign, and from then on you can use the name wherever you need the value. Variables let a program remember things: a score, a name, a total that grows while the program runs.

Creating variables

In Python there is no separate step to declare a variable. The first time you assign a value, the variable exists:

name = "Asha"
age = 21
height = 1.62
print(name, "is", age, "years old and", height, "m tall.")
Output
Asha is 21 years old and 1.62 m tall.

The = sign does not mean "is equal to" as in mathematics. It means "take the value on the right and store it under the name on the left". That is why x = x + 1 makes sense in a program: it takes the old value of x, adds one and stores the result back in x.

Changing a value

A variable can get a new value at any time, and even a value of another kind. The old value is forgotten:

score = 0
print("Start:", score)
score = score + 10
score += 5          # the same as score = score + 5
print("Now:", score)
score = "finished"
print("Later:", score)
Output
Start: 0
Now: 15
Later: finished

Python remembers what kind of value a variable holds at each moment, but it does not fix the kind once and for all. This is called dynamic typing.

Naming rules

A variable name may contain letters, digits and the underscore _, but it cannot start with a digit and cannot be a keyword such as if or for. Names are case-sensitive, so total and Total are different. By convention Python programmers write names in lower case, with underscores between words: first_name, total_price, max_speed. Choose names that say what the value means; price is much clearer than p.

Several values at once

You can assign several variables in one line, which also gives Python's famous one-line swap:

x, y, z = 1, 2, 3
print(x, y, z)
a = b = 0
print(a, b)
first, second = "left", "right"
first, second = second, first
print(first, second)
Output
1 2 3
0 0
right left

Practice exercises

  1. Create variables for your name, your city and your year of birth, and print a sentence that uses all three.
  2. Start a variable steps at 0, add 1000 three times with += and print the result.
  3. Swap the values of two variables a and b in one line and print them before and after.
  4. Try to create a variable called 2nd_place and read the error. Choose a valid name instead.