Variables and types — how a program remembers
Storing values in variables, the rules for naming them, and the four basic types — int, float, str, bool — plus the error beginners hit most often.
How do you want to learn?
The problem we are solving
So far our programs could remember nothing. Whatever was printed was gone.
Real work does not happen that way. In a billing program a price is calculated once and needed in three places. In a report a total has to be worked out first and used later. The program has to remember.
And there is a second problem alongside it. In the last chapter "2" + "3" gave 23 while 2 + 3 gave 5 — the same symbol, two behaviours. That is because in Python's eyes those two things are of different kinds. The kind is called a type, and the largest share of a beginner's errors come from here.
By the end of this chapter you can
- Store a value in a variable and change it later
- Choose names Python accepts, and that a human can read
- Recognise the four basic types:
int,float,str,bool - Inspect any value's type with
type() - Read a
TypeErrorand tell exactly what it is complaining about
Prerequisites: Seeing with print, explaining with comments.
A variable is a name
city_count = 4Read that line right to left: the value 4 came into existence, and the label city_count was attached to it. From now on, writing city_count hands you that value.
city_count = 4
print("Cities:", city_count)
print("Double:", city_count * 2)Cities: 4
Double: 8=does not mean equals. In mathematicsx = 4is a claim: x and 4 are the same. In Python=is an instruction: "store this value under that name." Which is whytotal = total + 5— impossible as mathematics — is perfectly ordinary Python. It means "take whattotalholds now, add 5, and put the result back intotal." Checking whether two things are equal has its own symbol,==, which we will meet later.
Changing a value
Assigning a new value to a variable leaves nothing of the old one:
stock = 20
print("Before:", stock)
stock = stock - 3
print("After:", stock)Before: 20
After: 17See what happens when two names point at the same value:
a = 10
b = a
a = 99
print(a, b)99 10The line b = a means: put the label b on the same value that a is attached to. Now both names refer to the same 10. Then a = 99 takes the label a off and puts it on the new value 99 — b stays where it was, on 10. Assigning a new value to one name moves only that name, not the other one.
Keep this picture in mind: two names can refer to the same value. With numbers and strings this causes no trouble, but later, when you learn lists — whose contents can be changed in place — this point becomes very important.
Rules for names
What Python will not accept:
- Starting with a digit:
2nd_priceis out,price_2is fine - A dash in the middle:
total-priceis out, Python reads it as subtraction - A space in the middle:
total priceis out - Python's keywords:
class,for,if,import,return,Nonecannot be used as names
What Python accepts but you should not write:
x1 = 4500 # clear today, meaningless in three weeks
Total_Price = 4500 # legal Python, but not the Python convention
l = 4500 # lowercase L and the digit one look almost identicalThe professional Python convention is snake_case — lowercase, with underscores between words:
total_price = 4500
customer_name = "Rafi"
items_in_cart = 3Fussing over names can feel like wasted time, but code is written once or twice and read twenty times. A name that explains itself does the work of a comment.
The four basic types
items = 7 # int — a whole number
price = 249.50 # float — a number with a decimal point
name = "Rafi" # str — text, inside quotes
is_paid = True # bool — only True or False
print(type(items))
print(type(price))
print(type(name))
print(type(is_paid))<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>type() is your instrument for settling doubt. When a variable behaves strangely, the first move is to print its type. Most of the time the answer is right there.
Two small but important notes:
True and False start with a capital letter. Write true and Python treats it as a variable name and reports that it does not know it.
"7" and 7 are not the same thing. The first is a string, the second is a number. They look alike and are completely distinct to Python:
a = 7
b = "7"
print(type(a), type(b))
print(a * 3)
print(b * 3)<class 'int'> <class 'str'>
21
777The error everyone gets
age = "22"
print(age + 1)Traceback (most recent call last):
File "C:\Users\Rafi\python-lab\lesson-04\demo.py", line 2, in <module>
print(age + 1)
~~~~^~~
TypeError: can only concatenate str (not "int") to strThe message looks intimidating and is in fact precise: only a str can be joined to a str, not an int. Python cannot tell whether you meant to add or to join — so rather than guess, it stopped.
The File line shows the full path of your own file, so it will be different on your computer. The other lines stay the same.
Read error messages from the bottom up. The last line says what is wrong; the line above it says where. Beginners often panic at the sight of a traceback and skip it entirely, but Python's error messages are the most helpful text on your screen.
The fix is to make the number a number:
age = "22"
print(int(age) + 1)23int() converts a string to a whole number. When that works and when it fails is covered properly in a later chapter on input(), because there this problem arrives every single time.
A complete example
invoice.py:
# Invoice for a single order, all figures in one place
customer_name = "Rafi"
unit_price = 249.50
quantity = 3
is_member = True
subtotal = unit_price * quantity
discount = 50.0
total = subtotal - discount
print("Customer :", customer_name)
print("Quantity :", quantity)
print("Subtotal :", subtotal)
print("Discount :", discount)
print("Total :", total)
print("Member :", is_member)Customer : Rafi
Quantity : 3
Subtotal : 748.5
Discount : 50.0
Total : 698.5
Member : TrueNotice where the real benefit is: to change the price you edit the unit_price line only, and every calculation below corrects itself. Had the numbers been typed straight into the print calls, you would have to hunt down every occurrence each time — and missing one makes the report wrong.
When it breaks
NameError: name 'total' is not defined The name you used has not been given a value yet, or it is misspelled. Python treats total and totl as two different names. Note that case matters too: Total is not total.
TypeError: can only concatenate str (not "int") to str You tried to join a number onto a string. Either convert with int(), or use a comma — print("Age:", age) — because print handles mixed types itself.
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? A dash in a name gives this. On the line total-price = 5, Python sees a calculation that subtracts price from total, and you cannot store a value into a calculation. Use an underscore: total_price.
SyntaxError: invalid syntax You tried to use one of Python's keywords as a name, such as class = 10. The message does not mention keywords; it only puts a ^ under the =, so you have to check yourself whether the name is a keyword. Pick another: class_name, grade.
NameError: name 'true' is not defined. Did you mean: 'True'? True and False start with a capital letter.
Step 4 of 6 — Predict
Check your understanding
What does this print?
a = 10
b = a
a = 99
print(a, b)- A10 99
- B10 10
- C99 99
- D99 10
Which of these is a valid Python variable name?
- Aclass
- Bitem-2
- C2nd_item
- Ditem_2
This program raises a TypeError. What exactly is wrong, and what fixes it?
age = "22"
next_year = age + 1
print("Next year:", next_year)- A`next_year` was used without being declared first
- B`age` holds a string, not a number — write `age = 22`, or use `int(age) + 1`
- CWriting `age + "1"` instead of `age + 1` would give 23
- DThe `print` needs a `+` instead of a comma
Answering needs an account
Sign in to check your answers
The questions are above, and working them out in your head is the part that matters. Sign in to see the answers, the explanations and the three-level hints.
Your turn
Write a file called shipping.py containing:
- Four variables — one
int, onefloat, onestr, onebool— all named meaningfully in snake_case - At least one calculation that uses two of them to produce a third variable
- The type of all four variables, printed with
type() - One variable that is given a value, then reassigned — printing the value at both steps
Then break it on purpose: take a str variable, write + 1 after it, and run the file. Read the whole error, especially the last line. You will meet that message many times; summoning it deliberately today makes it familiar later.
There is more in this mission
What you read above is the complete mission — nothing was cut out of it. Pro adds:
- What actually happens underneath — how Python runs this
- The full solution to the exercise, worked step by step
- Harder extra exercises
- The interview question on this topic, with a model answer
Step 6 of 6
Stretch — the chapter quiz
Ten questions from easy to hard. The last ones are difficult on purpose.
Sign in to take the quiz