Kodewick
Lesson 2 of 31Contents

Variables and types

Lesson 2 of 31 · Part 1 · Basics · about 15 minutes

A program needs to remember things: how many lamps are left, whose turn it is, what the player typed. A variable is a name you give to a value, so you can use it later.

Making a variable

Write a name, an = sign, and a value. From then on, the name stands for that value.

main.py
1name = "Wick"2lamps = 33print(name, "has", lamps, "lamps to light")
Output
Wick has 3 lamps to light

Here = does not mean "is equal to". It means store: work out the value on the right, then give it the name on the left. The name has no quotes, because it is not text; it is a label for something.

Changing a value

Assign to the same name again and the old value is replaced. The right side can even use the variable's own current value.

main.py
1oil = 102print(oil)3oil = 74print(oil)5oil = oil - 26print(oil)
Output
10
7
5

Read oil = oil - 2 from the right: take the current oil (7), subtract 2, store the result (5) back under oil.

Guess first

What does this print?

1a = 52b = a3a = 94print(b)

Naming rules

A name can use letters, digits and the underscore _. A few rules, and one habit:

RuleFineNot allowed
No spaceslamp_countlamp count
Cannot start with a digithouse22house
Only letters, digits and _total_costtotal-cost
Not a keywordclass_nameclass, if, True

Names are case-sensitive: lamps, Lamps and LAMPS are three different names. The usual Python style is lowercase words joined by underscores, like lamps_left. Pick names that say what the value is.

main.py
1lamp_count = 42print(lamp_count)3print(Lamp_count)
Output
4
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(Lamp_count)
NameError: name 'Lamp_count' is not defined. Did you mean: 'lamp_count'?

Using a name before it exists, or with a different capital letter, gives a NameError. Python even suggests the name you probably meant.

Types of values

Every value has a type, which says what kind of thing it is and what you can do with it. These five come up all the time:

TypeWhat it holdsExamples
inta whole number3, -12, 2026
floata number with a decimal point3.5, 0.1, -2.0
strtext (a string)"Wick", "42", ""
boolyes or noTrue, False
None"nothing here yet"None

The built-in type() tells you a value's type:

main.py
1print(type(42))2print(type(3.5))3print(type("42"))4print(type(True))5print(type(None))
Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>

Notice that "42" is a str, not an int: in quotes, it is just two characters. True, False and None start with a capital letter and have no quotes. The type of None is called NoneType, and None is its only value.

A variable has no fixed type. It holds whatever you last stored in it:

main.py
1thing = 422print(thing, type(thing))3thing = "forty-two"4print(thing, type(thing))
Output
42 <class 'int'>
forty-two <class 'str'>

Converting between types

Python will not guess what you mean when types are mixed. Text and a number cannot be added:

main.py
1stock = "30"2print(stock + 1)
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(stock + 1)
TypeError: can only concatenate str (not "int") to str

Convert first. Each type's name works as a function that makes a value of that type:

CallGivesExample
int(x)a whole numberint("12") is 12; int(3.9) is 3
float(x)a decimal numberfloat("2.5") is 2.5
str(x)textstr(7) is "7"
main.py
1print(int("30") + 1)2print(float("2.5"))3print(str(7) + " lamps")4print(int(3.9))5print(int("abc"))
Output
31
2.5
7 lamps
3
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(int("abc"))
ValueError: invalid literal for int() with base 10: 'abc'

int(3.9) cuts off the decimals; it does not round. And int("abc") fails with a ValueError: the type is right (a string), but there is no number in it.

Tip: TypeError means the kinds of values don't fit together. ValueError means the kind is right but the value itself is wrong.

f-strings

Joining text and numbers with commas works, but an f-string is usually clearer. Put an f before the opening quote, then write any variable or calculation inside { }:

main.py
1name = "Wick"2lamps = 33print(f"{name} has {lamps} lamps to light")4print(f"After one more: {lamps + 1}")5print("Without the f: {name}")
Output
Wick has 3 lamps to light
After one more: 4
Without the f: {name}

Python fills in each { } and turns the result into text for you, so there is no need for str(). Forget the f and the curly braces are printed as they are.

Swapping two variables

Sometimes two variables need to trade values. The obvious way does not work:

Guess first

What does this print?

1a = "red"2b = "blue"3a = b4b = a5print(a, b)

Python has a neat way to do it in one line. The right side is worked out first, then both names are given their new values together:

main.py
1a = "red"2b = "blue"3a, b = b, a4print(a, b)
Output
blue red

Practice

Write the code, then press Check. A hint costs nothing; the answer is there when you need it.

Exercise 1

Restock

The shop has stock lamps, stored as text. Add delivered to it and print the line below.

It should print
Lamps in stock: 12
exercise1.py
1stock = "8"2delivered = 43print("Lamps in stock:", stock)
Output
Press Run or Ctrl+Enter
Exercise 2

A sentence from variables

Use an f-string with name and age to print the sentence below.

It should print
Ada is 36 years old.
exercise2.py
1name = "Ada"2age = 363print(name, age)
Output
Press Run or Ctrl+Enter
Exercise 3

Trade places

Add one line so that the last line prints the two drinks the other way around.

It should print
coffee tea
exercise3.py
1first = "tea"2second = "coffee"3# your line here4print(first, second)
Output
Press Run or Ctrl+Enter

What you learned

  • name = value stores a value under a name; assigning again replaces it.
  • Names use letters, digits and _, cannot start with a digit, and are case-sensitive.
  • The basic types are int, float, str, bool and None; type() tells you which.
  • int(), float() and str() convert; mixing text and numbers without converting is a TypeError.
  • An f-string like f"{name} has {lamps}" puts values into text.
  • a, b = b, a swaps two variables.