🌱 Beginner

Numbers & Operators

📖 Lesson 04 ⏱ 25 min 🧪 5 questions 💻 3 exercises

🎯 Learning Objectives

  • Work with Python's numeric types: int, float, and complex
  • Use arithmetic operators: + - * / // % **
  • Understand operator precedence and use parentheses for clarity
  • Use comparison operators to produce boolean results
  • Apply augmented assignment operators (+=, *=, etc.)
  • Use the math module for common mathematical functions

Numeric Types

Python has three built-in numeric types:

TypeDescriptionExamples
intWhole numbers (unlimited precision)42, -7, 1_000_000
floatDecimal numbers (64-bit IEEE 754)3.14, -0.5, 6.022e23
complexComplex numbers (real + imaginary)3+4j, complex(1, 2)
# Integer literals
decimal = 255
hexadecimal = 0xFF      # 255
octal = 0o377           # 255
binary = 0b11111111     # 255
readable = 1_000_000    # underscores for readability

# Float literals
pi = 3.14159
avogadro = 6.022e23     # scientific notation
tiny = 1.6e-19

# Complex (rarely needed outside science/engineering)
z = 3 + 4j
print(z.real)   # 3.0
print(z.imag)   # 4.0
numeric_types.py
Python integers have arbitrary precision — they grow as large as your memory allows. 2 ** 1000 works perfectly and produces a 302-digit number. This is unlike C or Java where integers overflow at 32 or 64 bits.

Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division (true)10 / 33.3333…
//Floor division10 // 33
%Modulo (remainder)10 % 31
**Exponentiation2 ** 101024
# Division always returns a float
print(10 / 2)    # 5.0 (not 5)

# Floor division truncates toward negative infinity
print(7 // 2)    # 3
print(-7 // 2)   # -4 (floors down, not toward zero!)

# Modulo — remainder after floor division
print(17 % 5)    # 2
print(-17 % 5)   # 3 (result has the sign of the divisor)

# Exponentiation
print(2 ** 10)   # 1024
print(9 ** 0.5)  # 3.0 (square root)
arithmetic.py
/ always returns a float in Python 3, even for 10 / 25.0. Use // when you need an integer result.

Operator Precedence

Python evaluates expressions following this order (highest precedence first):

PriorityOperator(s)Description
1 (highest)**Exponentiation
2+x, -xUnary plus/minus
3*, /, //, %Multiplication, division, modulo
4+, -Addition, subtraction
5==, !=, <, >, <=, >=Comparisons
6notLogical NOT
7andLogical AND
8 (lowest)orLogical OR
# Without parentheses — follows precedence
result = 2 + 3 * 4      # 14 (not 20)
power = 2 ** 3 ** 2     # 512 (** is right-associative: 2^(3^2) = 2^9)

# Use parentheses for clarity
result = (2 + 3) * 4    # 20
average = (a + b + c) / 3
precedence.py
When in doubt, add parentheses. They cost nothing at runtime and make your intent crystal-clear to anyone reading the code — including future you.

Comparison Operators

Comparisons return a boolean (True or False):

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 5True
>Greater than5 > 3True
<=Less than or equal5 <= 5True
>=Greater than or equal3 >= 5False
x = 10

# Chained comparisons — Python's elegant feature
print(1 < x < 100)     # True (same as: 1 < x and x < 100)
print(0 <= x <= 10)    # True

# Comparing different numeric types works fine
print(5 == 5.0)        # True (int vs float)
print(1 == True)       # True (bool is a subclass of int)
comparisons.py
Python supports chained comparisons like 1 < x < 100. This is both more readable and more efficient than writing 1 < x and x < 100.

Augmented Assignment Operators

Shorthand for updating a variable in place:

OperatorEquivalent toExample
+=x = x + nscore += 10
-=x = x - nlives -= 1
*=x = x * ntotal *= 1.1
/=x = x / nprice /= 2
//=x = x // npages //= 2
%=x = x % nn %= 10
**=x = x ** nbase **= 2
score = 0
score += 10   # 10
score += 5    # 15
score *= 2    # 30
score -= 3    # 27
print(score)  # 27
augmented.py
Python does not have ++ or -- operators. Use x += 1 and x -= 1 instead.

Built-in Number Functions

print(abs(-42))        # 42  (absolute value)
print(round(3.7))      # 4   (banker's rounding)
print(round(3.14159, 2))  # 3.14
print(pow(2, 10))      # 1024 (same as 2 ** 10)
print(min(4, 1, 7))    # 1
print(max(4, 1, 7))    # 7
print(sum([1, 2, 3]))  # 6

# divmod returns (quotient, remainder) in one call
print(divmod(17, 5))   # (3, 2)
number_builtins.py

The math Module

Python's standard library includes the math module for advanced mathematical functions. Import it with import math.

import math

# Constants
print(math.pi)       # 3.141592653589793
print(math.e)        # 2.718281828459045
print(math.inf)      # infinity
print(math.nan)      # not a number

# Functions
print(math.sqrt(16))     # 4.0
print(math.ceil(3.2))    # 4   (round up)
print(math.floor(3.9))   # 3   (round down)
print(math.log(100, 10)) # 2.0 (log base 10)
print(math.log2(1024))   # 10.0
print(math.factorial(5)) # 120
print(math.gcd(48, 18))  # 6

# Trigonometry (radians)
print(math.sin(math.pi / 2))  # 1.0
print(math.cos(0))            # 1.0
angle = math.radians(45)      # convert degrees → radians
math_module.py
For money calculations, use the decimal module (exact decimal arithmetic) or fractions module (exact rational numbers) instead of float.

Common Gotchas

# Floating-point imprecision
print(0.1 + 0.2)           # 0.30000000000000004
print(0.1 + 0.2 == 0.3)   # False!

# Solution: compare with a tolerance
import math
print(math.isclose(0.1 + 0.2, 0.3))  # True

# Integer division by zero raises an error
# print(10 / 0)  → ZeroDivisionError

# Large floats lose precision
big = 10 ** 20
print(big + 1 == big)           # False (ints are exact)
print(float(big) + 1 == float(big))  # True! (float lost precision)
gotchas.py
🤖

Ask your AI tutor! Confused about floor division with negatives? Not sure when to use math.isclose()? These numeric edge cases trip up even experienced developers — ask and get a clear explanation.

💻 Exercises

01 Temperature Converter

Write a script that converts a temperature from Celsius to Fahrenheit. Formula: F = C × 9/5 + 32. Test with 0°C (should be 32°F) and 100°C (should be 212°F).

Show solution
celsius = 100
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius}°C = {fahrenheit}°F")
# 100°C = 212.0°F

celsius = 0
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius}°C = {fahrenheit}°F")
# 0°C = 32.0°F
02 Coin Breakdown

Given a total number of cents (e.g. 587), calculate the minimum number of coins needed using: quarters (25¢), dimes (10¢), nickels (5¢), pennies (1¢). Use // and %.

Show solution
total = 587

quarters = total // 25
total %= 25

dimes = total // 10
total %= 10

nickels = total // 5
total %= 5

pennies = total

print(f"Quarters: {quarters}")  # 23
print(f"Dimes:    {dimes}")     # 1
print(f"Nickels:  {nickels}")   # 0
print(f"Pennies:  {pennies}")   # 2
03 Distance Calculator

Given two points (x1, y1) and (x2, y2), calculate the Euclidean distance: √((x2−x1)² + (y2−y1)²). Use math.sqrt() or ** 0.5. Test with (0,0) and (3,4) — answer should be 5.0.

Show solution
import math

x1, y1 = 0, 0
x2, y2 = 3, 4

distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(f"Distance: {distance}")  # 5.0

# Alternative without math module:
distance2 = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"Distance: {distance2}")  # 5.0