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
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:
Operators on strings and lists
+ and * also work on sequences, where they mean “join” and “repeat”:
Comparison
Comparisons produce True or False.
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
Truthiness
Every value can be used where a boolean is expected. Empty things are falsy; everything else is truthy.
Short-circuiting
and and or stop as soon as the answer is known, and they return one of the operands, not
a boolean.
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.
The rule in practice: use == for values, and use is only with None, True and False.
Compound assignment
Watch the type: /= turns an int into a float and it never turns back.
Try it yourself
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.
Set label to the display name: use nickname if it has anything in it, otherwise full_name.
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 < 1is valid and readable. - Empty values are falsy; every other value is truthy — including the string
"0". and/orshort-circuit and return an operand, which makesvalue or defaultidiomatic.- Use
==for values and reserveisforNone,TrueandFalse.