Skip to content
skillbld
Day 4 of 14 30 minArithmeticComparisonBoolean logic

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.

Mind map · click a dot to fold, drag to pan

Arithmetic

main.py · editable
Output
Press Run to execute this code.
OperatorNameExampleResult
+ - *Add, subtract, multiply3 * 412
/Division (always float)8 / 24.0
//Floor division9 // 42
%Remainder (modulo)9 % 41
**Power2 ** 101024

// and % work as a pair. Here's how to turn minutes into hours and minutes:

main.py · editable
Output
Press Run to execute this code.

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.

Diagram
main.py · editable
Output
Press Run to execute this code.

Comparisons

Comparison operators ask a yes/no question and always produce a bool: True or False.

main.py · editable
Output
Press Run to execute this code.

Combining conditions: and, or, not

aba and ba or bnot a
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue
  • and is True only when both sides are True.
  • or is True when at least one side is True.
  • not flips True and False.
main.py · editable
Output
Press Run to execute this code.

Shortcut assignment

main.py · editable
Output
Press Run to execute this code.

Converting types

Input from users and files often arrives as text. Convert it before doing math:

main.py · editable
Output
Press Run to execute this code.

Recap

  • / always gives a float; // floors; % gives the remainder; ** is power.
  • Precedence: parentheses → ** → * / // % → + -.
  • Comparisons return True or False; == compares, = assigns.
  • and, or and not combine conditions.
  • Convert with int(), float() and str() before mixing types.

Knowledge check

Test what you learned

5 questions · pick an answer to see if you're right

0/5
  1. 1

    What is 7 // 2?

  2. 2

    What is 17 % 5?

  3. 3

    What does 2 + 3 * 4 evaluate to?

  4. 4

    What is the value of True and not False or False?

  5. 5

    What does int("42") + 1 give?

Finished today's lesson?