Foundations
Variables
Naming Values
You're tracking your monthly budget. Instead of typing 2500.00 every time you
calculate savings, rent, and groceries, you store it in a variable called income.
Now when your income changes, you update one number and all calculations adjust.
Store and use a value
Give a value a name, then use that name in calculations.
x =
print(x + 5)
print(x * x)
x =
print(x + 5)
print(x * x)
x =
print(x + 5)
print(x * x)
A variable holds a value. Use it anywhere you'd use the value itself.
Building expressions step by step
Break a complex calculation into named pieces. Each piece has meaning.
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
width =
height =
area = width * height
perimeter = 2 * (width + height)
Reading area tells you more than reading 7 * 5. Variables make code self-documenting.
Temperature conversion (Fahrenheit to Celsius)
Convert 98.6°F (body temperature) to Celsius using the formula: C = (F - 32) × 5 / 9
fahrenheit =
celsius = (fahrenheit - 32) * 5 / 9
fahrenheit =
celsius = (fahrenheit - 32) * 5 / 9
fahrenheit =
celsius = (fahrenheit - 32) * 5 / 9
fahrenheit =
celsius = (fahrenheit - 32) * 5 / 9
Variables make the formula readable: fahrenheit, celsius - you know what they mean.
Exercise: temperature_ex01.py
Write the reverse conversion: Celsius to Fahrenheit using F = C × 9/5 + 32
Fibonacci sequence (without loops)
Each Fibonacci number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8...
c0 = 0
c1 = 1
c2 = c0 + c1
c3 = c1 + c2
c4 = c2 + c3
c5 = c3 + c4
c6 = c4 + c5
c7 = c5 + c6
Watch how each variable depends on the previous ones. This pattern is called building up from base cases.
Circle calculations
Given a radius, calculate circumference and area.
pi = 3.14159
radius =
circumference = 2 * pi * radius
area = pi * radius * radius
pi = 3.14159
radius =
circumference = 2 * pi * radius
area = pi * radius * radius
pi = 3.14159
radius =
circumference = 2 * pi * radius
area = pi * radius * radius
pi = 3.14159
radius =
circumference = 2 * pi * radius
area = pi * radius * radius
pi and radius as named values make the formulas clear.
Exercise: circle_ex01.py
Extend to sphere: calculate volume (4/3 × π × r³) and surface area (4 × π × r²)