◀ Stage Select World 1 · Stage 1-03

Numbers, Text & Booleans

Knowing what kind of thing you are holding

Python cares a great deal about what type a value is. "7" and 7 look identical on screen and behave completely differently the moment you do anything with them. This stage covers the four types you will meet constantly, how to check which one you have, and how to convert on purpose rather than by accident.

Ready?

Step-by-step lessons

Four Types and the Traffic Between Them

Four short lessons: the two number types, text that looks numeric, converting deliberately, and the True/False type that everything in World 2 is built on.

1

Two Kinds of Number

An int is a whole number: 12, 0, -400. A float is a number with a decimal point: 4.5, 0.0, -12.75. The decimal point is the entire difference in how you write them.

type(value) tells you which you have. Python ints have no maximum size — you can multiply them until you run out of memory — which is unusual among programming languages and occasionally very convenient.

type(12)     # <class 'int'>
type(4.5)    # <class 'float'>
type(10 / 2) # <class 'float'>  — division always gives a float

Floats are approximations

Try 0.1 + 0.2 and Python answers 0.30000000000000004. That is not a bug, and it is not Python's fault: a computer stores decimals in binary, and 0.1 has no exact binary form, the same way 1/3 has no exact decimal form. The practical consequences are two. Never compare floats with == when the values came from arithmetic. And for money, either work in whole pence as an int, or format the output to two decimal places and accept the tiny error underneath.

Quick check

What type is the result of 10 / 5?

2

Text That Looks Like a Number Is Still Text

A str is text, written in matching quotes. "42" is a str whose two characters happen to be digits. Python will not quietly treat it as the number 42, and that refusal saves you from a whole family of bugs that other languages let through.

The clearest demonstration is +, which means two different things depending on what it is given:

"7" + "7"   # "77"  — text joined end to end
7 + 7       # 14    — numbers added
"7" + 7     # TypeError: can only concatenate str (not "int") to str

That TypeError is Python telling you the two values disagree about what kind of thing they are. The fix is never to force it — it is to convert one of them.

Anything typed by a person

Arrives as a str. Every time, with no exceptions.

Anything read from a file

Same. Files hold characters, not numbers.

Anything from a form or the web

Usually the same. Convert at the edge of your program.

Quick check

What does "3" * 2 produce?

3

Converting on Purpose

Each type has a function named after it that converts a value into it. This is usually called casting.

int("42")      # 42
float("4.5")   # 4.5
str(42)        # "42"
int(5.9)       # 5      — chopped, not rounded
round(5.9)     # 6      — rounded properly

That difference between int() and round() is worth stopping on. int() truncates: it removes the decimal part and keeps what is left, so 5.9 becomes 5. round() goes to the nearest whole number, so 5.9 becomes 6. Choosing the wrong one is how a calculation quietly loses a penny on every transaction.

Convert at the edge

Do the conversion at the point the value enters your program, not fifteen lines later where you happen to need a number. Then everything downstream is working with real types, and the one place that can fail is the one place you were expecting it to.

int("seven") does not return anything sensible — it raises a ValueError. That is the right behaviour: guessing would be worse.

Quick check

A price of 19.99 goes through int(price). What comes out?

4

True, False, and What Counts as Nothing

A bool holds one of exactly two values: True or False. Capital letter, no quotes — "True" in quotes is a five-letter word and behaves like one.

You rarely type True yourself. Bools mostly arrive as the answer to a comparison, and you store one when the question it answers has a good name:

is_adult = age >= 18
has_items = len(cart) > 0

Python will also give a True/False reading of any value, which it calls truthiness. The rule is short: things that are empty or zero are False, and everything else is True.

Falsy

Empty or zero

0, 0.0, "", [], {}, None

Truthy

Everything else

Any other number, any non-empty text — including "0" and "False", which are non-empty strings.

Why this matters next

Every if statement in World 2 asks exactly this question of whatever you give it. Knowing that an empty string is False and the string "0" is True saves you from a bug that is genuinely hard to spot by staring at the code.

Empty and zero are False. Everything else is True.

Quick check

What is bool("False")?

Type it yourself

Code Lab

Four exercises on telling Python's value types apart and converting between them on purpose.

0 of 4 cleared

Real Python runs right here in your browser — nothing to install, nothing sent to a server. The interpreter downloads once the first time you press Run, then stays cached.

01

One of each

To do

Almost everything you handle early on is one of four types. int is a whole number. float is a number with a decimal point. str is text in quotes. bool is True or False — capital letter, no quotes.

type(value) tells you which one you have, and type(value).__name__ gives you the bare name as text.

Your task: create four variables — count (the whole number 12), price (the decimal number 4.5), label (the text Tea), and in_stock (True). Then print the type name of each, one per line, giving int, float, str, bool.

your_code.py
Python
Hint

12 has no decimal point so it is an int; 4.5 has one so it is a float. True is written with a capital T and no quotes.

Output

      
    02

    Text that looks like a number

    To do

    "42" is text. It cannot be added to, doubled, or compared as a quantity — as far as Python is concerned it is a pair of characters that happen to be digits.

    int("42") converts it into the number 42, and float("4.5") does the same for decimals. Going the other way, str(42) turns a number into text.

    "7" + "7"   →  "77"   (text joined end to end)
    7 + 7 → 14 (numbers added)

    Your task: raw_age holds the text "29". Convert it to a whole number in a variable called age, then print age plus one. Output: 30.

    your_code.py
    Python
    Hint

    age = int(raw_age) converts it. Then print(age + 1).

    Output
    
          
      03

      Division always gives a float

      To do

      Plain division with / always produces a float, even when the answer is exact. 10 / 2 is 5.0, not 5.

      Sometimes you want the whole number back. int(5.9) gives 5 — note that it chops the decimal off rather than rounding, so 5.9 becomes 5 and not 6. When you do want rounding, that is round()'s job.

      Your task: divide total by people into share, then make whole_share the same value with the decimal chopped off, and rounded_share the same value rounded. Print all three, one per line.

      your_code.py
      Python
      Hint

      share = total / people gives 11.75. int(share) chops to 11; round(share) rounds to 12.

      Output
      
            
        04

        True, False, and empty

        To do

        A bool holds one of exactly two values: True or False. They are written with a capital letter and without quotes — "True" in quotes is just a five-letter word.

        bool(value) asks "does this count as something?". Python's answer is False for the empty and zero cases — 0, 0.0, "", None — and True for everything else. This becomes very useful in the next world, where if statements ask exactly that question.

        Your task: print the result of bool() on each of these four values, one per line, in this order: 0, 7, the empty text "", and the text "no".

        your_code.py
        Python
        Hint

        Zero and empty text are False; any other number and any non-empty text are True — including the word "no", because Python is checking for emptiness, not meaning.

        Output
        
              
          Boss round

          Assignment: Clean Up the Order

          One graded task. Pass every check and the stage is cleared and the title is yours — one more stage towards the Python Practitioner certificate.

          This one is graded. You can see 2 of the checks up front, and 3 stay hidden until you run. The hidden ones test the same job from angles you have not been shown, so code that genuinely solves the problem clears this and code shaped around the visible examples does not. Pass them all and the stage is yours.

          Clean up a messy order

          To do

          An order has arrived from a form where everything came through as text. Convert each field to the type it should be, work out the total, and print a tidy summary.

          The three raw values are already in the starter code. From them, create:

          • quantity — a whole number, from raw_quantity
          • unit_price — a decimal number, from raw_price
          • express — a bool, True only when raw_express is the text "yes"
          • totalquantity multiplied by unit_price

          Then print exactly three lines:

          Items: 3
          Express: True
          Total: 37.5

          Do not type 37.5 in by hand. One of the checks confirms the total really was worked out from the other two variables.

          your_code.py
          Python
          Hint

          int() and float() do the first two. For express, compare: raw_express == "yes" already produces True or False — no if statement needed. For the total, quantity * unit_price is the whole job.

          Output
          
                
            Lock it in

            Guess the Term

            Read the clues and name the concept. The fewer clues you need, the more points you score.

            Round 1 Score 0
            Keep it handy

            Data Types Quick Reference

            The whole stage on one screen.

            The Four Types

            7

            int

            Whole number. No size limit in Python.

            .5

            float

            Has a decimal point. Approximate, not exact.

            "

            str

            Text in matching quotes.

            T

            bool

            True or False, capitalised.

            Converting

            int("42")

            Text to whole number. ValueError if it isn't one.

            float("4.5")

            Text to decimal number.

            str(42)

            Anything to text.

            Whole Numbers

            int(5.9) is 5

            Truncates: the decimal part is dropped.

            round(5.9) is 6

            Goes to the nearest whole number.

            Money

            Work in whole pence, or format to 2dp on output.

            Truthiness

            Falsy

            0, 0.0, "", [], {}, None

            Truthy

            Everything else, including "0" and "False".

            type(x)

            Tells you what you actually have.

            Notification