Introduction
A variable is a name that points to a value. You create one with =, and Python remembers it until the program ends.
Without variables, a program could only work with values that were written into it. Variables let a program remember what it has read and worked out, so that one program can handle any input you give it.
How it works
Changing a variable
A variable can be given a new value at any time. The old value is simply replaced. Python can even swap two values in one line:
a = 1
b = 2
a, b = b, a
print(a, b)Step through line 3. Both variables change in the same step. The panel shows each old value crossed out next to the new one.
Text is a value too
Text in quotes is called a string. + joins two strings together:
name = "Rahim"
greeting = "Hello, " + name
print(greeting)Syntax
name = "Mitu" # create
age = 20
age = age + 1 # replace, using the old value
a, b = b, a # swap
Example
The line a = 5 means: work out the right side (5), then give it the name a. It does not mean "a equals 5" as in maths. It is an instruction, and it runs at one moment in time.
a = 5
b = 3
x = a + b
print(x)Press Visualize, then step through with the → key. Watch the right-hand panel:
- After line 1,
aappears with the value 5, marked new. - On line 3, the calculation box shows
a + b → 5 + 3 → 8: Python swaps each name for its value, then works out the result. - On line 4,
8appears in the output, at exactly the step that printed it.
Line by line
a = 5creates the nameafor the value 5.b = 3does the same forb.x = a + blooks up both names, works out 8, and then createsx.print(x)looks upxand shows 8.
Expected result
8
In the real world
A game keeps your score in a variable, and a shopping site keeps your cart's total in another. Good names make programs readable: total_price tells the next reader what x never could.
Common mistakes
- Using a variable before creating it gives a
NameError. Python runs top to bottom, so create it first. "5" + 3is aTypeError: you cannot add text and a number. Useint("5") + 3or"5" + str(3).- Names are case-sensitive:
Totalandtotalare two different variables.
Best practices
- Choose names that say what the value means.
- Use lower-case words joined with underscores, such as
total_marks. - Create a variable just before you need it.
Summary
= gives a name to a value, after working out the right side. A new value replaces the old one, and a, b = b, a swaps two values. Text and numbers cannot be added without converting one of them.
Practice
Change the first example so that it also prints the product a * b. Predict the output first, then run it and step through to check.
Quick check
Key takeaways
- The right side of = is worked out first, using the current values.
- A new value replaces the old one.
- Names are case-sensitive.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.