indusai.co

Numbers

Python has three numeric types. You will use int and float constantly; complex mostly appears in scientific code.

int

Whole numbers, positive or negative, with no size limit.

python
a = 42
b = -7
c = 123456789012345678901234567890
print(a, b, c)
print(c * c)

Underscores are allowed inside numbers to make them readable: 1_000_000.

float

Numbers with a decimal point, or written in scientific notation.

python
pi = 3.14159
tiny = 1.5e-3      # 0.0015
huge = 2.5e6       # 2500000.0
print(pi, tiny, huge)

complex

Written with a j for the imaginary part.

python
z = 3 + 4j
print(z.real, z.imag, abs(z))

Arithmetic

python
print(7 + 3)    # addition
print(7 - 3)    # subtraction
print(7 * 3)    # multiplication
print(7 / 3)    # division, always a float
print(7 // 3)   # floor division, rounds down
print(7 % 3)    # modulo, the remainder
print(7 ** 3)   # exponent

Two rules that surprise people:

  • / always returns a float, even 6 / 3 gives 2.0.
  • // rounds down, so -7 // 2 is -4, not -3.

Floating point precision

Floats are stored in binary, so some decimal fractions cannot be represented exactly.

python
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)

For money or anything where exactness matters, use the decimal module. For everything else, compare floats with a tolerance:

python
import math
print(math.isclose(0.1 + 0.2, 0.3))

Rounding

python
print(round(3.14159, 2))
print(round(2.5))    # rounds to the nearest even number
print(round(3.5))
print(int(3.99))     # int() truncates towards zero

Useful built in functions

python
print(abs(-5))
print(max(3, 9, 2))
print(min(3, 9, 2))
print(sum([1, 2, 3, 4]))
print(pow(2, 10))
print(divmod(17, 5))   # quotient and remainder together

The math module

python
import math

print(math.sqrt(16))
print(math.floor(3.7), math.ceil(3.2))
print(math.pi, math.e)
print(math.factorial(5))
print(math.log(100, 10))

Random numbers

python
import random

print(random.randint(1, 6))         # a dice roll
print(random.random())              # float between 0 and 1
print(random.choice(["a", "b", "c"]))

Practice

  1. Compute the area of a circle with radius 7 using math.pi, rounded to two decimal places.
  2. Use divmod to convert 500 minutes into hours and minutes.
  3. Write an expression that tells you whether 2024 is a leap year (divisible by 4, but not by 100 unless also by 400).