Skip to contentSkip to navigation

Module 02 · Lesson 01

Operators & Expressions

Calculate with arithmetic operators, compare values, combine conditions with and, or and not, check membership with in, and know the order Python applies them in.

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Calculate and share
  • Compare and combine
  • Order of operations
  • Watch the maths run

Python as a calculator

Operators are the symbols that do the work: they calculate, compare and combine values.

  • Calculate

    + - * / work like on a calculator. // keeps the whole part, % gives the leftover and ** is a power.

  • Compare

    == != < > <= >= ask a question and answer True or False.

  • Combine

    and, or and not join several True-or-False answers into one.

  • Order

    Brackets first, then **, then * / // %, then + -, then comparisons. Same idea as in maths.

Operators at work

A few symbols do a surprising amount of everyday work.

  • Clocks% wraps time around: 26 hours is 2 o'clock the next day, because 26 % 24 is 2.
  • Gamesscore >= 100 decides when the next world unlocks.
  • Shopsprice * quantity fills the basket total, and a comparison checks for free delivery.
  • Search boxes"cat" in title checks whether a word appears in the text you are searching.

Which part goes first?

One line, three operators. Tap each part to see the order Python works in.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

show:Shows the final answer, after everything inside the brackets is worked out.

Prints True

Calculate, compare, combine

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Calculator

The four everyday operators. Notice / always gives a decimal.

Your turn: Work out how many seconds are in a day with one line of *.

Python
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
Output
Press Run to see what it prints.

Watch apples go into bags

Press Step to run one line at a time. Each bag holds 5 apples.

Ready. Press Step to run the first line.

  1. apples = 17
  2. bags = apples // 5
  3. left = apples % 5
  4. full = bags * 5 + left == apples
  5. print(bags, "bags,", left, "left")
  6. print(full)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Odd or even?

print(9 % 2)

0 of 6 answered

Common operator misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Calculating, comparing and combining

An expression is any piece of code that Python can work out to a value, such as 3 + 4 or price * 2. The symbols that do the work are operators, and the values they work on are operands.

Arithmetic

You already know +, -, * and /. Python adds three more that turn out to be surprisingly useful.

Try it 1: edit me, then Run
print(17 / 5)    # 3.4   true division, always a float
print(17 // 5)   # 3     floor division, whole number of times
print(17 % 5)    # 2     remainder after dividing
print(2 ** 5)    # 32    power: 2 to the 5th
Output
Press Run to see what it prints.

Think of // and % as a pair. If you share 17 sweets among 5 children, each child gets 17 // 5, which is 3, and 17 % 5, which is 2, are left over. The remainder operator is also the standard way to test whether a number is even: n % 2 is 0 for even numbers and 1 for odd ones. It is handy for converting units too: 135 minutes is 135 // 60 hours and 135 % 60 minutes.

If either operand is a float, the result of +, -, *, // and % is a float as well, so 7.0 // 2 is 3.0.

Comparisons

A comparison asks a question and answers with a bool, True or False.

Try it 2: edit me, then Run
age = 15
print(age == 15)   # equal to
print(age != 15)   # not equal to
print(age >= 18)   # greater than or equal to
print(3 < age < 20)
Output
Press Run to see what it prints.

This prints True, False, False and True. The last line shows a Python nicety: comparisons can be chained, so 3 < age < 20 means "age is between 3 and 20". Remember that = assigns and == compares; mixing them up is one of the most common early mistakes.

Strings can be compared too. == checks that two strings are exactly the same, including capital letters, so "Yes" == "yes" is False. < and > compare strings in dictionary order, letter by letter, so "apple" < "banana" is True. Be careful: every capital letter sorts before every lowercase one, so "Zebra" < "apple" is also True. Comparing a number with a string using < is a TypeError, because Python has no sensible order between them, while == simply answers False.

Operators with assignment

Every arithmetic operator has an augmented form you met in the variables lesson: +=, -=, *=, /=, //=, %= and **=. Each one reads the variable, applies the operator with the value on the right and stores the result back, so pages //= 2 halves a page count and keeps it whole.

Combining conditions

Three logical operators combine bools.

  • a and b is True only when both are true.
  • a or b is True when at least one is true.
  • not a flips True to False and back.
Try it 3: edit me, then Run
age = 20
has_ticket = True
print(age >= 18 and has_ticket)
print(age < 12 or age > 65)
print(not has_ticket)
Output
Press Run to see what it prints.

Output: True, False, False. Python is lazy in a helpful way: with and, if the left side is already false it does not look at the right side, and with or, if the left side is already true it stops there. This is called short-circuit evaluation.

Membership and identity

in checks whether one value is inside another. For strings it looks for a piece of text: "cat" in "concatenate" is True. You will use in with lists and dictionaries later. not in is the opposite.

is checks whether two names refer to the very same object, which is different from being equal. Its everyday use is checking for the special value None, which means "no value": write result is None, not result == None. For numbers and strings, always compare with ==.

Order of operations

When an expression mixes operators, Python applies them in a fixed order called precedence. From first to last:

  1. Parentheses ( )
  2. Power **
  3. Multiplication and division: *, /, //, %
  4. Addition and subtraction: +, -
  5. Comparisons: ==, !=, <, >, <=, >=, in, is
  6. not, then and, then or

Operators at the same level run left to right, so 10 - 4 - 3 is 3. Power is the one exception: it runs right to left, so 2 ** 3 ** 2 is 2 ** 9, which is 512.

Try it 4: edit me, then Run
print(2 + 3 * 4)       # 14: * before +
print((2 + 3) * 4)     # 20: parentheses first
print(-3 ** 2)         # -9: ** before the minus sign
Output
Press Run to see what it prints.

The order of logical operators matters as well. not binds tighter than and, and and binds tighter than or, so True or False and False is True, because the and runs first. When an expression mixes several operators, add parentheses even when they are not strictly needed. They cost nothing and make the intended order obvious to every reader, including you in a month.

A classic precedence bug is the average of two numbers. a + b / 2 divides only b by two. The correct version is (a + b) / 2.

Syntax

The general shape of the statements in this lesson.

syntax.py
+  -  *  /         # add, subtract, multiply, divide (float)
//  %  **          # floor division, remainder, power
==  !=  <  >  <=  >=   # comparisons give True or False
and  or  not       # combine bools
"a" in "cat"       # membership
x is None          # identity, for None checks
(a + b) / 2        # parentheses control the order
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Converting minutes to hours and minutes

Beginner

A film lasts 135 minutes. Show it as hours and minutes, and say whether the length in minutes is an even number.

Python
film = 135
hours = film // 60
minutes = film % 60
print(hours, "h", minutes, "min")
print("Even length:", film % 2 == 0)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

// counts whole hours and % gives the minutes left over, the same pair you would use for sweets and children. film % 2 == 0 is a comparison, so it prints a bool. Because % runs before ==, no parentheses are needed, though adding them would not hurt.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Using = instead of ==

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
score = 10
print(score = 10)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError, because print() has no keyword argument called score

Write this instead

score = 10
print(score == 10)

Why it happens

A single = inside a call is read as setting a keyword argument, not as a comparison.

In the real world

Where this shows up in software people use every day.

  1. Packing eggs into boxes

    Farming

    A small farm collects eggs every morning and packs them into boxes of six. The farmer wants to know how many full boxes there are and how many eggs are left for the kitchen.

    Why Python fits

    Floor division and remainder answer the two packing questions in one line each, and a comparison turns the result into a yes or no decision.

    Python
    EGGS_PER_BOX = 6
    collected = 83
    full_boxes = collected // EGGS_PER_BOX
    spare = collected % EGGS_PER_BOX
    print("Full boxes:", full_boxes)
    print("Spare eggs:", spare)
    print("Enough for market:", full_boxes >= 12)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

What does // do with negative numbers?

It rounds down towards negative infinity, so -7 // 2 is -4, not -3. The matching remainder -7 % 2 is 1.

Why is 0.1 + 0.2 == 0.3 False?

Floats are stored approximately, so the sum is 0.30000000000000004. Compare rounded values, as in round(0.1 + 0.2, 2) == 0.3.

Should I use and or the & symbol?

Use and for conditions. & is a different operator that works on the bits of numbers, which you will rarely need.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/5 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.