Skip to content

Python Foundations·Lesson 4 of 67·beginner

Operators and expressions

Arithmetic, comparison, logic and assignment — plus the integer division and truthiness rules that surprise people.


In this lesson · 12 min

  • →Use arithmetic operators including floor division and modulo
  • →Compare and combine values with comparison and boolean operators
  • →Understand truthiness and short-circuit evaluation
  • →Know when to use `is` instead of `==`

An expression is anything that produces a value. 2 + 2 is an expression; so is name.upper() and score > 0.9. Operators are how you build them.

Arithmetic

PythonPython not started

Two of those deserve attention.

/ always returns a float, even when the answer is whole. 10 / 2 is 5.0, not 5. Use // when you want an integer result.

% (modulo) gives the remainder, and it is more useful than it looks:

PythonPython not started

Operators on strings and lists

+ and * also work on sequences, where they mean “join” and “repeat”:

PythonPython not started

Comparison

Comparisons produce True or False.

PythonPython not started

That chained form is genuinely Python-specific and worth using — 0.8 <= score < 0.9 is clearer than score >= 0.8 and score < 0.9.

Boolean logic

PythonPython not started

Truthiness

Every value can be used where a boolean is expected. Empty things are falsy; everything else is truthy.

PythonPython not started

Short-circuiting

and and or stop as soon as the answer is known, and they return one of the operands, not a boolean.

PythonPython not started

That last pattern — value or fallback — is idiomatic Python for “use this unless it’s empty”.

== versus is

== asks “are these equal?”. is asks “are these the same object?”. They are not the same question.

PythonPython not started

The rule in practice: use == for values, and use is only with None, True and False.

PythonPython not started

Compound assignment

PythonPython not started

Watch the type: /= turns an int into a float and it never turns back.

Try it yourself

Exercise 1

A job has 1,000 items processed in batches of 32. Print the number of full batches and the size of the final partial batch, on two lines.

Your turnPython not started
Exercise 2

Set label to the display name: use nickname if it has anything in it, otherwise full_name.

Your turnPython not started

Check yourself

What is the value of 7 // 2 + 7 % 2?

Recap

  • / always gives a float; // floors to an int; % gives the remainder.
  • Comparisons chain: 0 <= x < 1 is valid and readable.
  • Empty values are falsy; every other value is truthy — including the string "0".
  • and/or short-circuit and return an operand, which makes value or default idiomatic.
  • Use == for values and reserve is for None, True and False.
Next: Lists →