Expressions, Numbers, and Operations
This is the most fundamental page in the main Python track. The goal isn't to memorize every operator, but to build a few solid impressions first:
- What are the common numeric types in Python
- What
+ - * / // % **actually do - Where it's easy to get the syntax right but the result wrong
Common Numeric Types
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
In everyday development, you'll encounter int and float most often.
Basic Operators
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 % 3) # 1
print(10 ** 3) # 1000
Three distinctions I remind myself of most often
/: True division, result is usually a float//: Floor division, keeps only the integer part of the quotient%: Modulo (remainder)
Operator Precedence
As in most languages, multiplication and division take priority over addition and subtraction; when in doubt, just add parentheses.
result = 2 + 3 * 4 # 14
result = (2 + 3) * 4 # 20
My own habit: whenever an expression gets even slightly long, I proactively add parentheses for clarity rather than betting on my memory of precedence rules.
Comparison and Logical Operators
print(3 > 2) # True
print(3 == 2) # False
print(3 > 2 and 5 > 1) # True
print(3 > 2 or 5 < 1) # True
print(not (3 > 2)) # False
The easiest thing to mix up here:
=is assignment==is the equality check
Common Built-in Math Functions
print(abs(-10)) # 10
print(round(3.14159, 2)) # 3.14
print(pow(2, 5)) # 32
print(divmod(10, 3)) # (3, 1)
For basic math operations, built-in functions are more than enough; for more systematic math functions, see the math module.
Common items from the math module
import math
print(math.sqrt(16)) # 4.0
print(math.floor(3.8)) # 3
print(math.ceil(3.2)) # 4
print(math.pi) # 3.141592653589793
Don't idealize floating-point numbers
It's easy for beginners to assume 0.1 + 0.2 should exactly equal 0.3, but floating-point numbers don't work that way:
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
A safer way to compare floats is to check whether the difference is small enough:
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
A more practical way to think about it
For this section, I prioritize remembering the following:
- Distinguish
/,//,%in numeric operations first - Add parentheses when expressions get longer
- Don't use
==for float comparisons - Think of
abs(),round(),divmod(), andmathfirst for common math tools