Sub topic 1
Expressions, Operands, and Operators
Prerequisites
You should know basic Python syntax, variables, assignment, and the types int, float, str, bool, list, and dict. You should also be able to run a Python script or use the REPL.
Expressions, operands, and operators
An expression is code that Python evaluates to produce a value. An operand is a value that an operator uses. An operator is a symbol or keyword that performs an operation.
In total + tax, total and tax are operands, and + is the operator. Parentheses can make the intended grouping clear.
Arithmetic operators
Python provides these common arithmetic operators:
+adds-subtracts*multiplies**raises to a power/performs true division//performs floor division%returns a remainder
print(2 + 3 * 4) # 14
print(2 ** 10) # 1024
print(7 / 2) # 3.5Multiplication has higher precedence than addition, so 2 + 3 * 4 means 2 + (3 * 4). Use parentheses when grouping matters.
Division, floor division, and modulo
True division always returns a float. Floor division rounds down toward negative infinity, not toward zero. Modulo returns the remainder, with the sign of the divisor.
print(7 // 2) # 3
print(-7 // 2) # -4
print(-7 % 2) # 1
print(divmod(-7, 2)) # (-4, 1)The result follows this relationship: a == (a // b) * b + (a % b) when b is nonzero.
Floating-point precision and `math.isclose`
Binary floating-point numbers cannot represent every decimal fraction exactly. Therefore, direct equality can surprise you.
import math
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # TrueUse math.isclose when comparing calculated floating-point values.
Comparison operators
Comparisons produce True or False. Python supports ==, !=, <, <=, >, and >=.
Chained comparisons
A chained comparison combines related tests. 1 < x < 10 means 1 < x and x < 10, and x is evaluated once.
x = 5
print(1 < x < 10) # TrueExercise
What do -7 // 2 and -7 % 2 evaluate to?
Show answer
-4 and 1. Floor division rounds down, and the remainder satisfies -7 == (-4 * 2) + 1.