Python Variables Examples
Short, runnable programs that show python variables in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Variables lesson.
1One value, several names
x = y = z = 0 points three names at the same starting value. Reassigning one of them later moves only that name.
x = y = z = 0
x = 5
print(x, y, z)Expected output5 0 0
2Swapping: the long way and the Python way
Many languages need a temporary variable to swap two values. Python can do it in one line, because the whole right side is evaluated before any name changes.
a = "tea"
b = "coffee"
temp = a # the long way: keep a copy of a
a = b
b = temp
print(a, b)
a, b = b, a # the Python way: one line
print(a, b)Expected outputcoffee tea
tea coffee
3A name can move to a different type
Python doesn't fix a variable's type. Here answer first refers to a number, then to text. type() (next lesson) shows which kind of value the name points to.
answer = 42
print(answer, type(answer))
answer = "forty-two"
print(answer, type(answer))Expected output42 <class 'int'>
forty-two <class 'str'>
4Constants written in capitals
Python has no true constants, but a name in ALL_CAPS tells other programmers "this value is fixed — don't change it".
VAT_RATE = 0.2 # capitals: a value that should not change
price = 40
vat = price * VAT_RATE
print("VAT:", vat)
print("Total:", price + vat)Expected outputVAT: 8.0
Total: 48.0
Practise next
Python Variables exercises → Back to the lesson
Python Data Types examplesPython Operators examplesPython Variable Scope examples