Numbers and Math
20 min In ProgressLearning Objectives
- Use integers and floats
- Perform arithmetic operations
- Understand operator precedence
- Write comments to document code
Integers and Floats
Python has two main numeric types: integers (whole numbers) and floats (decimal numbers).
x = 10 # integer
y = 3.14 # float
print(type(x))
print(type(y))
Arithmetic Operators
Python supports standard math operators: +, -, *, /, // (floor division), % (modulo), and ** (exponent).
a = 17
b = 5
print(a + b) # 22
print(a - b) # 12
print(a * b) # 85
print(a / b) # 3.4
print(a // b) # 3
print(a % b) # 2
print(a ** b) # 1419857
Course Example: Calculate Speed
This example converts distance and time into multiple speed units using arithmetic.
distance_in_km = 150
time_in_hours = 2
distance_in_mi = distance_in_km / 1.6
distance_in_mtrs = distance_in_km * 1000
time_in_seconds = time_in_hours * 3600
speed_in_kph = distance_in_km / time_in_hours
speed_in_mph = distance_in_mi / time_in_hours
speed_in_mps = distance_in_mtrs / time_in_seconds
print("The speed in kilometers per hour is:", speed_in_kph)
print("The speed in miles per hour is:", speed_in_mph)
print("The speed in meters per second is:", speed_in_mps)
Course Example: Circle Calculations
Using a constant and the exponent operator to compute circle properties.
PI = 3.14159
radius = 7
area = PI * radius**2
circumference = 2 * PI * radius
print("Circumference of the circle:", circumference)
print("Area of the circle:", area)
📝 Exercise: Temperature Converter
Write a script that converts a Celsius temperature to Fahrenheit using the formula: F = (C × 9/5) + 32.
code.py
Output