Python supports integers, floating-point numbers, and complex numbers. Most beginner programs use the first two.
Basic operators#
a = 7
b = 2
print(a + b) # 9
print(a - b) # 5
print(a * b) # 14
print(a / b) # 3.5
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 49/always produces a float.//performs floor division and keeps the integer type when both operands are integers.%returns the remainder.**raises the left value to the power of the right value.
Precedence and parentheses#
Exponentiation runs before multiplication and division, which run before addition and subtraction. Parentheses override precedence.
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
print(2 ** 3 ** 2) # 512: right-associative
print(-2 ** 2) # -4: exponentiation binds firstWhen a formula is not obvious, add parentheses. They cost nothing and make intent clear.
Integers do not overflow#
Python integers have arbitrary precision. They grow as needed, limited only by memory:
print(2 ** 100)1267650600228229401496703205376
Floats follow IEEE 754 double precision and can lose exactness.
Floating-point numbers#
Some decimal values cannot be represented exactly in binary. The result is a tiny rounding error:
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)0.30000000000000004 False
For display, format the value:
total = 0.1 + 0.2
print(f"{total:.2f}")0.30
For money, store integer cents or use the decimal module when exact decimal arithmetic is required.
Useful numeric functions#
import math
print(abs(-9)) # 9
print(round(3.14159, 2)) # 3.14
print(math.sqrt(81)) # 9.0
print(math.floor(3.9)) # 3
print(math.ceil(3.1)) # 4round() uses banker's rounding for exact ties. Do not rely on it for financial calculations.
Try it#
Compute the area and circumference of a circle with radius 4.5. Format both answers to two decimal places. Then compute the average of 12, 19, and 7 as a float and as a formatted string.
