01 Numbers & Variables
▾int (whole numbers) and float (decimals).
//— integer division (rounds down)/— true division (always returns float)%— modulo (remainder)**— power (exponentiation)
/ which always → float).Any operation with a float → float.
= is assignment. == is comparison.
7 // 2
7 / 2
7 % 3
2 ** 10
type(3)
type(3.0)
type(3 / 1)
10 + 3 * 2
17 % 5
2 ** 0
Calculate the area and volume of a rectangular prism with width=7.3, length=15.1, height=6.
You have 1342 eggs. How many gross (144), dozens (12), and singles?
Experiment freely with operators:
02 Using Functions
▾import math— access viamath.sqrt()from math import *— imports everything, callsqrt()directlyimport math as m— alias, callm.sqrt()from math import sin, cos— import specific functions
math.sqrt(), math.sin(), math.cos(), math.radians(), math.pi, round(), abs()
Random:
random.randint(a, b), random.uniform(a, b)
print() displays a value but returns None.Functions can be nested:
math.sin(math.radians(45))
print(print(3))
print(3) displays 3, returns None. Outer print displays None.
import math; math.floor(3.9)
round(3.14159, 2)
abs(-7)
Calculate 2 × cos(π/6) rounded to 4 decimal places.
Simulate rolling 2 dice and print the total.
Risk dice: attacker rolls 3 dice, keeps the top 2. Print all 3 rolls and the kept total.
03 Strings — Basics
▾'...' or "...". Escape characters:
\n— new line\t— tab\\— literal backslash\'— apostrophe inside single quotes\"— quote inside double quotes
+ concatenates strings (no space).print(a, b) adds a space between a and b.'abc' * 3 → 'abcabcabc'\n counts as 1 character in len().
number = 2; print('The number is', number)
print('What\'s', 'the display?')
print('Some things are', 'double'*2 + ',')
print('others are', 'triple'*3 + '.')
print('How do you obtain\na new line?')
\n creates an actual line break in the output.
print('one\n\ttwotwo\none\ttwotwo')
print('Is one the same as \"one\"?')
x = 1; y = 2; print('the sum of', x, 'and', y, 'is equal to', x+y)
x = 'one'; y = 'two'
print('Does \"' + x, y + '\" = \"' + x + y + '\"?')
+ concatenates (no space), comma in print adds a space.
Build a box around "The answer is 42" using +, *, and \n.
Experiment with string operations:
04 Booleans & Decisions
▾==, !=, <, >, <=, >=Logical operators:
and, or, not
not binds tightest, then and, then or.Think of
and like multiplication and or like addition.Common mistake:
= (assignment) vs == (comparison).Truthiness:
0, 0.0, '', [] are False. Everything else is True.
True or False
1 < 2 or 1 > 2
1 < 2 and 1 > 2
(1 != 2 and 'a' == 'a') or 2 == 3
1 != 2 and 'a' == 'a' or 2 == 3
and binds first: (True and True) or False → True
(1 != 2 or 'a' == 'a') and 2 == 3
1 != 2 or 'a' == 'a' and 2 == 3
and binds first: True or (True and False) → True or False → True
(1 < 2 or 3 == 3) and (1 == 0 or 1 != 1)
1 < 2 or 3 == 3 and 1 == 0 or 1 != 1
True or (True and False) or False → True or False or False → True
(1 < 2 and 3 == 3) or (1 == 0 and 1 != 1)
1 < 2 and 3 == 3 or 1 == 0 and 1 != 1
(True and True) or (False and False) → True or False → True
True or False and True or False and True or False
True or (F and T) or (F and T) or F → True or F or F or F → True
x = 5
if x > 3:
print('big')
else:
print('small')
x = 5
if x > 10:
print('A')
elif x > 3:
print('B')
else:
print('C')
x = 7
if x > 5:
print('A')
if x > 3:
print('B')
Two separate if statements — both can trigger.
x = 0
if x:
print('truthy')
else:
print('falsy')
0 is falsy in Python.
s = ''
if s:
print('has content')
else:
print('empty')
Letter grade program: convert a mark (0-100) to A/B/C/D/E/F.
Discount calculator: 10% off over $100, additional 5% off over $200.
05 While Loops
▾True.
1. Variable in test must be defined before the loop.
2. The loop body must update the test variable (or it runs forever!).
3. Loop body is indented.
Accumulator pattern:
total = 0 before loop, total += value inside.Shorthand:
x += 1 is the same as x = x + 1
k = 1
while k <= 3:
print(k)
k += 1
total = 0; k = 1
while k <= 4:
total += k
k += 1
print(total)
1 + 2 + 3 + 4 = 10
n = 8
while n > 1:
n = n // 2
print(n)
Print the squares of 1 through 10.
Calculate the sum of squares from 1 to N (try N=10).
Integer division using repeated subtraction (compute a // b without using //).
GCD using the Euclidean algorithm.
06 Lists
▾[1, 2, 3]
list[i]— access element at index i (0-based)list[-1]— last elementlist[a:b]— slice from index a to b-1append(),insert(),remove(),pop(),sort()len(),sum(),min(),max()
Tuples
(1, 2, 3) are immutable — once created, cannot be changed.list.index(x) returns the position of x in the list.
a = [10, 20, 30, 40, 50]; print(a[0])
a = [10, 20, 30, 40, 50]; print(a[-1])
a = [10, 20, 30, 40, 50]; print(a[1:3])
a = [10, 20, 30, 40, 50]; print(a[:2])
a = [10, 20, 30, 40, 50]; print(a[3:])
a = [3, 1, 4, 1, 5]; a.sort(); print(a)
a = [1, 2, 3]; a.append(4); print(len(a))
a = [1, 2, 3]; b = a.pop(); print(b, a)
Generate 10 random numbers (1-100), find min, max, and average.
Build a list of squares from 1 to 20.
07 For Loops
▾range(n)→ 0, 1, 2, ..., n-1range(a, b)→ a, a+1, ..., b-1range(a, b, step)→ a, a+step, a+2*step, ... (while < b)enumerate(list)→ gives both index and value
[expr for x in sequence]Compact way to build a list in one line.
Example:
[x**2 for x in range(5)] → [0, 1, 4, 9, 16]
[x**2 for x in range(5)]
list(range(3, 8))
list(range(0, 10, 3))
list(range(5, 0, -1))
[c.upper() for c in 'hello']
Sum of the first 100 positive integers using a for loop.
Print a multiplication table (1-5).
Use a list comprehension to get squares of even numbers from 0 to 20.
Enumerate: print each fruit with its index.
08 Strings — Advanced
▾f"Hello {name}"String methods:
.split()— split into list by whitespace (or given delimiter)' '.join(list)— join list items with a separator.upper(),.lower()— case conversion.replace(old, new)— replace substrings.find(sub)— find position of substring (-1 if not found).strip()— remove leading/trailing whitespace
s[a:b] works just like list slicing.s[::-1] reverses the string.Strings are immutable — methods return new strings.
name = 'Alice'; f"Hello, {name}!"
x = 3; f"{x} squared is {x**2}"
'hello world'.split()
'-'.join(['a', 'b', 'c'])
'Python'[::-1]
'hello'.replace('l', 'L')
'banana'.find('nan')
Reverse a string using slicing.
Count the vowels in a string.
Experiment with f-strings and string methods.
09 Functions
▾def function_name(parameters):Returning a value:
return value
print() displays a value on screen. return sends a value back to the caller.A function without
return returns None.Scope: Variables inside a function are local — they don't exist outside.
Order: A function must be defined before it is called.
Default arguments:
def greet(name='World')
def add(a, b):
return a + b
print(add(3, 4))
def add(a, b):
print(a + b)
result = add(3, 4)
print(result)
print() inside the function displays 7, but the function returns None.
x = 10
def change():
x = 20
change()
print(x)
x inside the function is local — it doesn't affect the global x.
def greet(name='World'):
return f'Hello, {name}!'
print(greet())
print(greet('Alice'))
Write an is_even(n) function that returns True if n is even.
Write factorial(n) using recursion.
Write distance(x1, y1, x2, y2) that computes the Euclidean distance.
Challenge: write a function that checks if a number is prime.
10 Exam Prep Workbook
▾Quick Reference Card
f-strings: f"text {variable} more {expression:.2f}" sum/max/min: sum(list), max(list), min(list), list.index(max(list)) while pattern: total=0; i=0; while i<n: total+=item; i+=1 bool precedence: not > and > or (like: NOT > * > +) slicing: s[start:stop:step], s[::-1] reverses
Topic 1: String Formatting & f-strings
f and put expressions inside {}.Format specifiers go after a colon inside the braces:
:.2f— 2 decimal places (float):>10— right-align in 10 characters:<10— left-align in 10 characters:^10— center in 10 characters:08d— zero-pad to 8 digits
f"Pi is {3.14159:.2f}" → "Pi is 3.14"f"{'hello':>20}" → right-aligned in 20 charsYou can put any expression inside the braces:
f"{2 + 3}" → "5"
Exercise 1: Given price = 19.99, produce the string "The price is $19.99" using an f-string.
Exercise 2: Format a table row: name left-aligned in 15 characters, grade right-aligned in 5 characters. Test with name="Alice", grade="A+".
Exercise 3: Build a receipt with aligned columns: item name (left, 20 chars), quantity (right, 5), unit price (right, 8, 2 decimals), total (right, 10, 2 decimals).
Topic 2: List Operations
list[i]— access by index,list[-1]— last elementlist[a:b]— slice,list[::-1]— reverseappend(),insert(i, x),remove(x),pop()sum(),max(),min(),len(),sorted()list.index(x)— find position of value x
highest = max(scores)position = scores.index(highest)
Exercise 1: Given scores = [88, 92, 75, 98, 84], find the highest score and its position (index).
Exercise 2: Remove duplicates from [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] while preserving order.
Exercise 3: Compute the running average of [10, 20, 30, 40, 50]. After each element, print the average of all elements seen so far.
Topic 3: While Loop Patterns
- Counter:
i = 0; while i < n: ...; i += 1 - Accumulator:
total = 0; while ...: total += value - Sentinel: Loop until a special value is encountered
- Validation: Keep asking until input is valid
1. Loop variable initialized before the loop
2. Loop variable updated inside the loop
3. Condition will eventually become
False
Exercise 1: Sum the integers from 1 to 100 using a while loop.
Exercise 2: Input validation loop — keep asking for a number between 1 and 10. (Simulated with a pre-set list of attempts.)
Exercise 3: Collatz conjecture — starting from n, if even: n = n/2, if odd: n = 3n+1. Count steps to reach 1. Try n=27.
Topic 4: Boolean Logic & Operator Precedence
True and True→ True |True and False→ FalseTrue or False→ True |False or False→ Falsenot True→ False |not False→ True
not > and > orThink of it like arithmetic:
not = unary minus, and = multiplication, or = addition.Short-circuit evaluation:
True or X → True (X is never evaluated)False and X → False (X is never evaluated)
Evaluate these 15 expressions mentally, then click to reveal the answer:
True or False
1 < 2 or 1 > 2
1 < 2 and 1 > 2
(1 != 2 and 'a'=='a') or 2 == 3
1 != 2 and 'a'=='a' or 2 == 3
(1 != 2 or 'a'=='a') and 2 == 3
1 != 2 or 'a'=='a' and 2 == 3
TRICKY — and binds first: True or (True and False) → True
(1 < 2 or 3 == 3) and (1 == 0 or 1 != 1)
1 < 2 or 3 == 3 and 1 == 0 or 1 != 1
(1 < 2 and 3 == 3) or (1 == 0 and 1 != 1)
1 < 2 and 3 == 3 or 1 == 0 and 1 != 1
True or False and True or False and True or False
not True and False or True
(not True) and False or True → False and False or True → True
not (True and False) or True
not (True or False) and True
not True and True → False and True → False
Verify your answers:
Topic 5: Writing Functions
def function_name(params):— define a functionreturn value— send a value back to the callerprint()displays but returnsNone- Variables inside a function are local (not visible outside)
def greet(name='World')— default argument
print() instead of return.If you need to use the result later, the function must
return it.print() is only for displaying to the screen.
Exercise 1: Write is_palindrome(s) that checks if a string reads the same forwards and backwards.
Exercise 2: Write letter_grade(mark) that returns A (90+), B (80+), C (70+), D (60+), E (50+), or F.
Exercise 3: Write fibonacci(n) that returns the nth Fibonacci number (0, 1, 1, 2, 3, 5, 8, ...).