◀ Stage Select World 1 · Stage 1-06

Math & Comparisons

The operators every decision is built from

Arithmetic you mostly know already, apart from two operators that turn out to do a surprising amount of work. Comparisons and logic you may not — and every if statement, every loop condition and every filter in the rest of this track is made of them. Clear this and World 1 is complete.

Ready?

Step-by-step lessons

Arithmetic, Questions, and Logic

Four short lessons: the arithmetic operators including the two beginners skip, comparisons that produce True or False, combining conditions with and/or/not, and the order Python does everything in.

1

Seven Arithmetic Operators, Two Worth Dwelling On

17 + 5    # 22
17 - 5    # 12
17 * 5    # 85
17 / 5    # 3.4   true division — always a float
17 // 5   # 3     floor division — the whole part
17 % 5    # 2     modulo — the remainder
17 ** 2   # 289   power

// and % are the two most people skip, and they are the two that earn their keep. Together they answer one question: how many whole ones fit, and what is left over?

Unit conversion

seconds // 60 whole minutes, seconds % 60 the leftover seconds.

Grouping

items // per_page full pages, items % per_page the last partial one.

Divisibility

n % 2 == 0 asks whether n is even. Any remainder of zero means it divides cleanly.

Cycling

index % length turns a rising counter into a repeating loop through positions.

Everyday example, splitting the bill

47 sweets between 5 children. 47 / 5 is 9.4, which is a true answer and completely useless — nobody hands out four tenths of a sweet. 47 // 5 is 9 each, and 47 % 5 is the 2 left in the bag. Those are the two numbers a person actually needs.

Quick check

You have 100 items and show 8 per page. Which expression gives the number of items on the final, partly-filled page?

2

Comparisons: Questions With Two Possible Answers

A comparison asks something about two values and hands back a bool. There are six, and they behave exactly as they look:

a == b    equal to
a != b    not equal to
a <  b    less than
a <= b    less than or equal to
a >  b    greater than
a >= b    greater than or equal to

The one that catches people is == against =. One equals sign is an instruction that changes something. Two is a question that changes nothing.

Changes something

score = 100

Assignment. Score is now 100, whatever it was before.

Asks something

score == 100

Comparison. Produces True or False and leaves score alone.

Python also lets you chain comparisons the way maths notation does, which most languages do not allow:

0 <= score <= 100      # both conditions, reads as written
low < value < high

Quick check

A pass mark is 60 and a score of exactly 60 should pass. Which comparison is right?

3

Joining Conditions Together

Three words combine conditions. Python spells them out rather than using symbols, which means a condition can be read aloud and checked against the requirement it came from.

and

Both sides must be true

signed_in and not suspended

or

At least one side must be true

is_student or is_member

not

Flips whatever follows

not suspended

Python evaluates these lazily, which is called short-circuiting. In a and b, if a is already False then nothing b could be would make the whole thing true, so b is never evaluated at all. or does the mirror image: a True on the left settles it.

Short-circuiting is a safety feature

It means the order of your conditions matters, and you can use that deliberately. Put the check that protects the risky part on the left:

if items and items[0] == "tea":

On an empty list, items is falsy, so Python stops and never touches items[0] — which would have raised an IndexError. Swap the two sides and the same line crashes.

Quick check

A member may train when they are signed in and have not been suspended. Which line says that?

4

What Python Does First

Python does not read an expression left to right. It follows a precedence order — the school rules, extended:

1.  ()              brackets
2.  **              power
3.  * / // %        multiply and divide
4.  + -             add and subtract
5.  == != < <= > >= comparisons
6.  not
7.  and
8.  or

So 2 + 3 * 4 is 14, not 20. And because comparisons come after arithmetic, total > 10 * 2 compares total against 20 rather than doubling anything. Because and beats or, the line a or b and c means a or (b and c) — which is very rarely what someone typing it quickly intended.

Brackets are free

Nobody has ever been slowed down by a pair of brackets that made an expression obvious. Plenty of people have lost an afternoon to a condition that turned out to group differently from how it read. If a line needs a moment's thought, add them — you are writing for the person who reads it next, and that person is usually you.

When in doubt, bracket it. The cost is two characters.

Quick check

What does 2 + 3 * 4 ** 2 come to?

Type it yourself

Code Lab

Four exercises on arithmetic, comparisons and logic — the operators every condition and every calculation in the rest of this track is built from.

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

The two kinds of division

To do

Python has three division-shaped operators and they answer different questions.

17 / 5    →  3.4   true division, always a float
17 // 5 → 3 floor division, the whole part
17 % 5 → 2 modulo, the remainder

// and % are a pair: together they answer "how many whole ones fit, and what is left over?". That single idea handles splitting things into groups, converting units, and checking whether a number divides evenly.

Your task: 47 sweets are shared between 5 children. Work out each (how many each child gets), left_over (how many remain), and exact (the true division result). Print all three, one per line.

your_code.py
Python
Hint

// gives the whole number of sweets each child gets, % gives what is left in the bag, and / gives the fractional answer nobody can actually hand out.

Output

      
    02

    Questions that answer True or False

    To do

    A comparison asks a question and hands back a bool. There are six of them:

    a == b   equal to        a != b   not equal to
    a < b less than a <= b less than or equal
    a > b greater than a >= b greater than or equal

    The one to watch is == against =. A single equals sign assigns — it changes something. A double equals sign asks — it changes nothing and produces True or False.

    Python also lets you chain comparisons the way maths does: 0 <= score <= 100 means both at once, and reads exactly as it looks.

    Your task: with score at 72 and pass_mark at 60, work out passed (is the score at least the pass mark?), perfect (is it exactly 100?), and in_range (is it between 0 and 100 inclusive, written as one chained comparison). Print all three.

    your_code.py
    Python
    Hint

    "At least" means >=, not >. For in_range, write it as one chain: 0 <= score <= 100.

    Output
    
          
      03

      Combining conditions

      To do

      Three words join conditions together. and needs both sides true. or needs at least one. not flips whatever follows it.

      True  and False   →  False
      True or False → True
      not True → False

      Python is lazy about these, in a useful way. In a and b, if a is already False there is no way the whole thing can be true, so b is never evaluated at all. That is called short-circuiting, and it is what lets you write a safety check first and the risky part second.

      Your task: a member can train when they are signed in and have not been suspended. They get a discount when they are either a student or a member. Work out can_train and gets_discount from the four flags given, and print both.

      your_code.py
      Python
      Hint

      "Has not been suspended" is `not suspended`. Join it to signed_in with `and`. The discount is is_student or is_member.

      Output
      
            
        04

        What happens first

        To do

        Python does not read left to right. It follows the same precedence rules you learned in school, extended a little:

        1. ()          brackets
        2. ** power
        3. * / // % multiply and divide
        4. + - add and subtract
        5. == != < > comparisons
        6. not, and, or

        So 2 + 3 * 4 is 14, not 20. And because comparisons happen after arithmetic, total > 10 * 2 compares against 20 rather than doubling the answer.

        Brackets beat all of it, and cost nothing. When a line needs a moment's thought to read, add them.

        Your task: the same four numbers, three different answers. Set plain to the value of 2 + 3 * 4 ** 2 exactly as written, bracketed to the value of that expression with brackets forcing strict left-to-right order, and average to the mean of 4, 8 and 12. Print all three.

        your_code.py
        Python
        Hint

        Power first, then multiply, then add: 3 * 4 ** 2 is 3 * 16. For strict left to right, bracket every step: ((2 + 3) * 4) ** 2. For the average, remember to bracket the sum before dividing.

        Output
        
              
          Boss round

          Assignment: The Session Clock

          One graded task. Pass every check and the stage is cleared and the title is yours. Clear this and World 1 is complete.

          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.

          Break a session time down

          To do

          A training session lasted total_seconds. Turn that single number into hours, minutes and seconds, and report on it.

          Work out these variables from total_seconds alone:

          • hours — whole hours in the total
          • minutes — whole minutes left after the hours are taken out
          • seconds — seconds left after that
          • is_long — True when the session ran an hour or more
          • exact_minutes — the total as a decimal number of minutes

          Then print exactly three lines:

          1h 26m 45s
          Exact minutes: 86.75
          Long session: True

          The middle line shows two decimal places. Everything must be calculated — the hidden checks re-derive each value from total_seconds, so typed-in answers will not pass.

          your_code.py
          Python
          Hint

          // and % in turn: hours is total_seconds // 3600, and total_seconds % 3600 is what remains, which you then split the same way with // 60 and % 60. is_long is a comparison, so it needs no if statement.

          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

            Operators Quick Reference

            The whole stage on one screen.

            Arithmetic

            /

            True division

            Always a float. 10 / 2 is 5.0.

            //

            Floor division

            The whole part. "How many fit?"

            %

            Modulo

            The remainder. "What is left?"

            **

            Power

            9 ** 0.5 is also a square root.

            Comparisons

            ==

            Equal to

            Asks. = assigns — a different thing entirely.

            !=

            Not equal to

            The opposite of ==.

            >=

            At least

            Includes the boundary. > does not.

            <<

            Chaining

            0 <= n <= 100 means both at once.

            Logic

            and

            Both

            False on the left and the right never runs.

            or

            Either

            True on the left and the right never runs.

            not

            Flip

            Applies to whatever follows it.

            Precedence

            1

            () then **

            Brackets beat everything.

            2

            * / // % then + -

            Multiply before add, as at school.

            3

            Comparisons

            After all the arithmetic.

            4

            not, and, or

            Last, in that order.

            Notification