Do math, compare values and combine conditions. Learn how Python evaluates expressions and why 7 / 2 isn't 3.
By the end of today you can
- Use arithmetic operators, including //, % and **
- Predict the result of an expression using operator precedence
- Compare values and combine conditions with and, or and not
- Convert between int, float and str
An expression is anything Python can work out to a value: 2 + 3, price * 1.2, age >= 18. Today you'll learn the operators that build expressions and the rules Python follows to evaluate them.
Arithmetic
| Operator | Name | Example | Result |
|---|---|---|---|
+ - * | Add, subtract, multiply | 3 * 4 | 12 |
/ | Division (always float) | 8 / 2 | 4.0 |
// | Floor division | 9 // 4 | 2 |
% | Remainder (modulo) | 9 % 4 | 1 |
** | Power | 2 ** 10 | 1024 |
// and % work as a pair. Here's how to turn minutes into hours and minutes:
Order of operations
Python follows the same precedence rules as math: parentheses, then powers, then multiply/divide, then add/subtract. Operators with the same precedence run left to right.
Comparisons
Comparison operators ask a yes/no question and always produce a bool: True or False.
Combining conditions: and, or, not
| a | b | a and b | a or b | not a |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
andis True only when both sides are True.oris True when at least one side is True.notflips True and False.
Shortcut assignment
Converting types
Input from users and files often arrives as text. Convert it before doing math:
Recap
/always gives a float;//floors;%gives the remainder;**is power.- Precedence: parentheses →
**→* / // %→+ -. - Comparisons return
TrueorFalse;==compares,=assigns. and,orandnotcombine conditions.- Convert with
int(),float()andstr()before mixing types.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
What is 7 // 2?
- 2
What is 17 % 5?
- 3
What does 2 + 3 * 4 evaluate to?
- 4
What is the value of True and not False or False?
- 5
What does int("42") + 1 give?
Finished today's lesson?