Python, properly · Chapter 2 of 42

Variables and types

By the end of this chapter you can give a value a name, know which of Python's basic types a value is, change what a name stands for, and fix the errors that come from mixing types. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: First steps
  • 4 tasks
  • Python
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

In chapter 1 every program printed text you typed into it. A real bill is not like that: the price of a Veg Thali is 210 today and 220 next month, and the number of tiffins in the kitchen changes every few minutes. Farah wants programs that remember values and work with them, so that when a price changes, it changes in one place.

To do that, a program needs names for its values, and it needs to know what kind of value each one is: a number you can add, text you can print, a yes or no. That is this chapter.

The lesson

A name is a label on a value

special = "Veg Thali"
price = 210
print(special, price)
Veg Thali 210

The = here is not "equals" from maths. It is assignment: Python works out the value on the right, then puts the name on the left on it. From then on, writing special means that value. A name for a value is called a variable.

Think of each value as a tiffin on a shelf and each name as a paper tag tied to it. The tag is not the tiffin; it only tells you which tiffin to pick up. In the REPL, typing a name shows the value it is tied to:

>>> special = "Veg Thali"
>>> price = 210
>>> special
'Veg Thali'
>>> price
210

Five types of value

Every value has a type, and the type decides what you can do with it. type() asks Python:

>>> type(210)
<class 'int'>
>>> type(4.5)
<class 'float'>
>>> type("Veg Thali")
<class 'str'>
>>> type("210")
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(None)
<class 'NoneType'>
  • int (integer): a whole number, like 210 or -5. No quotes, no point.
  • float: a number with a decimal point, like 4.5. Chapter 3 shows why floats need care with money.
  • str (string): text, always in quotes. "210" is text: it looks like a number, but to Python it is three characters.
  • bool: True or False, with capital letters. A yes or no, like "is this dish available?".
  • None: Python's word for "no value yet", like a discount that does not exist. print(None) shows None.

The type matters because the same operator does different things:

>>> 7 + 5
12
>>> "7" + "5"
'75'
>>> "7" * 3
'777'

Numbers add; text joins. A price read from a sheet as "210" will not add up until it becomes a number (chapter 5).

Changing a name: reassignment

A name can be moved to a new value at any time. Python always works out the right side first, using the old value, and only then moves the name:

orders = 12
print("Orders so far:", orders)
orders = orders + 1
print("Orders so far:", orders)
orders += 5
print("Orders so far:", orders)
Orders so far: 12
Orders so far: 13
Orders so far: 18

orders = orders + 1 reads as "take what orders is now, add 1, and tie the name to the result". orders += 5 is the short form; -= takes away. The old value 12 is not changed: the tag simply moved to 13.

Two names, one value

What happens when you assign one name to another?

special = "Veg Thali"
board = special
special = "Chole"
>>> special
'Chole'
>>> board
'Veg Thali'
>>> board is special
False

board = special does not copy anything and does not tie the two names together. It ties a second tag to the value special was on at that moment. Moving special later moves only that one tag; board stays where it was.

  • == asks "are these two values equal?".
  • is asks "are these two names on the same value?". You will use it mostly to ask discount is None. It matters most with lists, in chapter 8, where two names on one list is a famous trap.

Rules for names

A name is letters, digits and underscores, it cannot start with a digit, and it has no spaces. Python's own words, like class or if, are taken:

  File "/workspace/chapters/02-variables-and-types/badname.py", line 1
    2nd_rider = "Imran"
    ^
SyntaxError: invalid decimal literal

Names are case-sensitive: Price and price are two different names. Python style (PEP 8) writes them in small letters with underscores, snake_case: rider_name, total_today.

A name must also be made before it is used, because the file runs from the top:

Traceback (most recent call last):
  File "/workspace/chapters/02-variables-and-types/before.py", line 1, in <module>
    print("Rider:", rider)
NameError: name 'rider' is not defined

Mixing types: TypeError

+ cannot join text and a number. Python refuses rather than guess:

price = 210
print("Veg Thali costs Rs " + price)
Traceback (most recent call last):
  File "/workspace/chapters/02-variables-and-types/mix.py", line 2, in <module>
    print("Veg Thali costs Rs " + price)
TypeError: can only concatenate str (not "int") to str

"Concatenate" means join. A TypeError says an operation got a value of the wrong type. The easy fix is the one from chapter 1: give print the text and the number as two values, and it shows each one.

print("Veg Thali costs Rs", price)
Veg Thali costs Rs 210

Your turn

Your four tasks are at the top. Task 1's check looks at the type of each name, so watch your quotes and capitals; task 3 is the label trap in miniature. The interview question is a bill with three classic beginner mistakes: fix them one traceback at a time.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    dish.py: one dish, five names

    Farah wants one dish described in code, so that later programs can use it. In dish.py make exactly these five names:

    dish: the text Rajma Chawal

    price: the whole number 170

    rating: the decimal number 4.5

    available: True

    discount: None (there is no discount yet)

    Then print the dish and its price, so the program shows exactly one line:

    Rajma Chawal 170

    The check imports your file and looks at the type of each name, so a price written in quotes is text, not a number.

  2. Task 2

    tiffins.py: one name, three values

    Bhavna counts tiffins through the morning. Start with a name tiffins for 50 tiffins and print it. Then 18 go out with riders: change tiffins by taking 18 from itself, and print it. Then the kitchen packs 6 more: add 6 to it, and print it. The output is exactly:

    Tiffins: 50

    Tiffins: 32

    Tiffins: 38

    Let Python do the sums: the numbers 32 and 38 must not appear in your code.

  3. Task 3

    riders.py: two names, one rider

    The rider board has a morning name and an evening name. Make morning the text Santosh Kamble, then make evening label the same value by assigning morning to it (write the rider's name only once in your code). Then the morning shift changes: make morning the text Imran Shaikh. Print the two shifts, so the output is exactly:

    Morning: Imran Shaikh

    Evening: Santosh Kamble

  4. Task 4 · interview question

    Interview: fix_bill.py, three type and name mistakes

    fix_bill.py prints a bill but stops with an error. Run it, read each traceback, fix the line it points at, and run it again until it prints exactly:

    Order D0042

    Items: 3

    Rider: Santosh Kamble

    Total: Rs 375

    Keep the four print lines and the names order_id, rider_name, items and total; do not type 375 into a print.

What you will learn

  • Assignment: name = value, and why a name is a label, not a box.
  • Types: int, float, str, bool and None, and type().
  • Reassignment: moving a name to a new value, += and -=.
  • Two names, one value: what board = special really does, and is.
  • Rules for names and the TypeError from mixing text and numbers.

More in First steps

Build "Variables and types" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.