Part of Python for Beginners

Python Tutorial for Beginners #4 - Numbers & Math (All 7 Operators, Math Module, Built-ins)

Sandy LaneSandy Lane

Video: Python Tutorial for Beginners #4 - Numbers & Math (All 7 Operators, Math Module, Built-ins) by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Python Numbers & Math

Seven operators: + - * / // % **. The math module for sqrt, floor, ceil, pi. Built-ins: abs, round, min, max, sum. The / and // distinction matters.

Python's numeric handling is convenient: integers are unbounded, division has two flavors (true and floor), and the math module covers everything else.

The seven arithmetic operators

a, b = 10, 3
print(f"{a} + {b} = {a + b}")    # 13
print(f"{a} - {b} = {a - b}")    # 7
print(f"{a} * {b} = {a * b}")    # 30
print(f"{a} / {b} = {a / b}")    # 3.3333... (true division)
print(f"{a} // {b} = {a // b}")  # 3 (floor division)
print(f"{a} % {b} = {a % b}")    # 1 (modulo)
print(f"{a} ** {b} = {a ** b}")  # 1000 (exponent)

Seven operators. The unusual ones for C/Java programmers:

  • / always returns float — 10 / 2 is 5.0, not 5.
  • // is floor division — 10 // 3 is 3. Truncates toward negative infinity.
  • ** is exponent — 2 ** 10 is 1024. (^ is XOR, not power.)

True vs floor division

print(10 / 3)      # 3.3333333333333335 (float)
print(10 // 3)     # 3 (int)
print(10.0 / 3)    # 3.3333... (float, both ways)
print(10.0 // 3)   # 3.0 (float, but truncated)

print(-10 // 3)    # -4 (NOT -3 — toward negative infinity)

// rounds toward negative infinity. -10 // 3 is -4, not -3. Different from C, where integer division truncates toward zero.

For C-style truncation, use int(-10 / 3)-3, or math.trunc.

Modulo

print(10 % 3)     # 1
print(-10 % 3)    # 2 (NOT -1 — Python's % matches divisor's sign)

Python's % always has the same sign as the divisor. -10 % 3 is 2 (because -10 = -4*3 + 2). C's would be -1.

For "remainder always positive when divisor is positive," Python's behavior is what you usually want.

Compound assignment

count = 0
count += 5    # count = count + 5
count *= 2    # count = count * 2
count //= 3   # count = count // 3
print(count)

All seven operators have compound forms: +=, -=, *=, /=, //=, %=, **=.

The math module

import math

math.sqrt(16)         # 4.0
math.sqrt(2)          # 1.4142135623730951
math.ceil(4.2)        # 5
math.floor(4.8)       # 4
math.pi               # 3.141592653589793
math.e                # 2.718281828459045
math.pow(2, 10)       # 1024.0 (always float)
math.log(100, 10)     # 2.0 (log base 10)
math.log(math.e)      # 1.0 (natural log)
math.sin(math.pi / 2) # 1.0

math.sqrt, math.pow, math.log, math.sin/cos/tan, math.exp, math.factorial, etc.

math.pi and math.e are constants.

math.pow(x, y) returns float; x ** y returns int when both are ints.

Built-in numeric functions

abs(-42)       # 42
abs(3.14)      # 3.14

round(3.14)    # 3
round(3.7)     # 4
round(3.5)     # 4 (banker's rounding — to even)
round(2.5)     # 2 (also to even!)
round(3.14159, 2)   # 3.14 (2 decimals)

min(5, 2, 8)   # 2
max(5, 2, 8)   # 8
sum([1, 2, 3]) # 6

# With iterables
numbers = [5, 2, 8, 1, 9]
print(min(numbers), max(numbers), sum(numbers))

abs, round, min, max, sum — built-ins, no import needed.

round(2.5) returns 2, not 3 — Python uses banker's rounding (round half to even). Surprises everyone the first time. For traditional rounding, int(x + 0.5) for positive numbers (or use math.floor(x + 0.5)).

Integer vs float

type(10)         # int
type(10.0)       # float
type(10 / 5)     # float (always)
type(10 // 5)    # int (when both operands are int)
type(10.0 // 5)  # float

10 == 10.0       # True (different types, equal value)

Mixing int and float gives float. int(3.7) truncates to 3 (toward zero). float(5) is 5.0.

Big integers

huge = 2 ** 1000
print(huge)
print(len(str(huge)))   # 302 digits

Python ints are unbounded — automatically use as much memory as needed. C and most other languages have a 32 or 64-bit ceiling.

The cost: Python int ops are slower than C int ops. For numerical performance, use NumPy.

Number conversion

int(3.7)         # 3 (truncates toward zero)
int("42")        # 42
int("ff", 16)    # 255 (hex)
int("1010", 2)   # 10 (binary)

float(3)         # 3.0
float("3.14")    # 3.14

bin(10)          # '0b1010'
hex(255)         # '0xff'
oct(8)           # '0o10'

int(s, base) parses with a custom base (2, 8, 16, etc.). bin, hex, oct produce string representations.

Floating-point gotcha

print(0.1 + 0.2)        # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False

Floating-point can't represent 0.1 exactly in binary. Sums accumulate tiny errors.

For comparisons, use a tolerance:

import math
math.isclose(0.1 + 0.2, 0.3)   # True

For exact decimal arithmetic (money, scientific):

from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))   # 0.3 exactly

Random numbers

import random

random.random()           # 0.0 to 1.0 (float)
random.randint(1, 10)     # int 1-10 inclusive
random.uniform(0, 1)      # float 0-1
random.choice([1, 2, 3])  # picks one
random.shuffle(my_list)   # in-place shuffle

random.seed(42)            # reproducible randomness

random for general use. For cryptographic randomness, use secrets (since Python 3.6).

Common stumbles

/ returning float. 10 / 2 is 5.0, not 5. Use // for integer result.

Banker's rounding. round(0.5) is 0, not 1. Use int(x + 0.5) for traditional rounding (positive numbers).

Modulo with negatives. Python's % matches the divisor sign. C's matches dividend.

Float comparison. Never use == for floats. Use math.isclose or compare to a tolerance.

^ for power. ^ is XOR (5 ^ 3 is 6). Use ** for exponentiation.

Mixing int and str. 5 + "5" errors. Convert: 5 + int("5") or f"{5}{5}".

What's next

Lesson 5: user input and output. input(), formatted print, and a temperature-converter mini-project.

Recap

Seven operators: + - * / // % **. / is true division (always float); // is floor division (toward negative infinity). % matches divisor sign. ** is exponent. math module: sqrt, floor, ceil, pi, log, trig. Built-ins: abs, round (banker's), min, max, sum. Integers are unbounded. For exact decimal math, Decimal. For float comparison, math.isclose.

Next lesson: input and output.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.