Module 1, topic 3, week 2, Tuesday
Loops and functions
for and while loops, break and continue, functions, parameters, return values, scope and recursion
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 31 solved problems, ready to run and change.
topic-03-loops-and-functions.ipynb, 97 KB
Practice notebook
The 15 practice problems with examples of input and output, a hint and a hidden solution for each.
topic-03-practice.ipynb, 28 KB
Introduction: why do we need loops?
This lesson is a beginner-friendly guide to repeating work with loops (for and while) and organizing code with functions (parameters, return values, and scope). It explains every concept in simple language, compares the tools with each other, and then walks through 31 solved problems from easy to medium-hard, including factorial and Fibonacci in loop and recursion versions. At the end there are practice problems.
You should already know variables, data types, operators, and if/else. The examples use numbers, text, and Boolean values only.
What you will learn
- 1.Why loops exist and how
forandwhilework - 2.The differences between
forandwhile, and when to use each - 3.
break,continue, and nested loops - 4.What functions are and why they beat repeating code
- 5.Parameters, arguments, return values, and scope
- 6.Lambda functions: small functions written in one line
- 7.Recursion (a function that calls itself) and how it compares with loops
- 8.31 solved problems and practice problems
Imagine you must print "Hello" five times. Without loops you copy and paste:
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")Output
Hello Hello Hello Hello Hello
Now imagine 1,000 times. That is not realistic. A loop repeats a block of code for you:
for i in range(5):
print("Hello")Output
Hello Hello Hello Hello Hello
Change it and run: change 5 to 10. One number controls how often the block runs.
Loops are used whenever a task repeats: adding up numbers, checking every character of a word, repeating a question until the user answers correctly, running a game until it ends, and so on.
Python has two kinds of loops:
forloop: repeats a known number of times.whileloop: repeats as long as a condition is True.
1The for loop
1.1Syntax
for variable in sequence:
# code that repeatsThe most common "sequence" is range(), which produces numbers.
for number in range(5):
print(number)Output
0 1 2 3 4
Change it and run: change 5 to 3, then to 1. What is always the first number?
Notice that range(5) gives 0, 1, 2, 3, 4. It starts at 0 and stops before 5.
1.2How range() works
| Code | Numbers produced | Meaning |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | from 0 up to (not including) 5 |
| range(1, 6) | 1, 2, 3, 4, 5 | from 1 up to (not including) 6 |
| range(0, 10, 2) | 0, 2, 4, 6, 8 | the third number is the step |
| range(10, 0, -2) | 10, 8, 6, 4, 2 | a negative step counts down |
| range(5, 1) | nothing | start is already past the end |
To see all the numbers of a range at once, wrap it in list() (lists are the topic of the next lesson):
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 10, 2)))
print(list(range(10, 0, -2)))
print(list(range(5, 1)))Output
[0, 1, 2, 3, 4] [1, 2, 3, 4, 5] [0, 2, 4, 6, 8] [10, 8, 6, 4, 2] []
for number in range(1, 6):
print(number)Output
1 2 3 4 5
for number in range(10, 0, -3):
print(number)Output
10 7 4 1
Change it and run: change the step from -3 to -2. Is 0 ever printed?
Change start, stop and step, and watch which numbers the loop visits.
for number in range(1, 6, 1):
print(number)Numbers produced (5)
- 1
- 2
- 3
- 4
- 5
- 6
It starts at 1, moves by 1 each time, and stops before it reaches 6. The stop value (crossed out) is never included.
1.3How Python runs a for loop
For for i in range(3): Python does this:
- Put the first value (0) into
i, run the block. - Put the next value (1) into
i, run the block. - Put the next value (2) into
i, run the block. - No values are left, so the loop ends and Python continues below it.
Each run of the block is called an iteration. The variable (i, number, anything you like) is called the loop variable.
1.4Looping over text
A string is a sequence of characters, so a for loop can visit each character:
for letter in "Python":
print(letter)Output
P y t h o n
Change it and run: put your own name between the quotes.
1.5The accumulator pattern (adding things up)
A very common job is to collect a result as the loop runs. Create a variable before the loop, and update it inside:
total = 0
for i in range(1, 6):
total = total + i
print("Total:", total)Output
Total: 15
Change it and run: change range(1, 6) to range(1, 11). The total becomes 55.
Here is what happens step by step (a trace table):
| Iteration | i | total after the update |
|---|---|---|
| start | 0 | |
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
| 5 | 5 | 15 |
Trace the loop: one step at a time
- 1total = 0
- 2for i in range(1, 6):
- 3 total = total + i
- 4print("Total:", total)
Press “Next step” to start.
Tracing a loop on paper like this is the best way to understand and debug it.
1.6Printing on the same line
print() normally ends with a new line. Use end=" " to put a space instead:
for number in range(1, 6):
print(number, end=" ")
print()Output
1 2 3 4 5
Change it and run: change end=" " to end=", ".
The empty print() at the end moves to a new line.
1.7Useful facts about for
- If the range is empty (like
range(5, 1)), the loop body runs zero times. - After the loop, the loop variable keeps its last value.
- If you don't need the loop variable, many programmers name it
_:for _ in range(3):.
for number in range(5, 1):
print(number)
print("The loop body ran zero times.")Output
The loop body ran zero times.
for number in range(1, 4):
print(number)
print("After the loop, number is still", number)Output
1 2 3 After the loop, number is still 3
for _ in range(3):
print("Hi")Output
Hi Hi Hi
Try it yourself
for loop, each on its own line.Show a hint
range(10, 0, -1). The stop value 0 is not included.Show the solution
for number in range(10, 0, -1):
print(number)Output
10 9 8 7 6 5 4 3 2 1
Try it yourself
Show a hint
end=" " keeps the numbers on one line; finish with an empty print().Show the solution
for number in range(1, 30, 2):
print(number, end=" ")
print()Output
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
Try it yourself
6 x 1 = 6.Show a hint
i over range(1, 11) and print the number, i and their product.Show the solution
number = 6
for i in range(1, 11):
print(number, "x", i, "=", number * i)Output
6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30 6 x 6 = 36 6 x 7 = 42 6 x 8 = 48 6 x 9 = 54 6 x 10 = 60
2The while loop
2.1Syntax
while condition:
# code that repeats as long as the condition is TrueA while loop works like an if statement that keeps coming back. Python checks the condition. If it is True, it runs the block and then checks the condition again. When the condition becomes False, the loop stops.
count = 1
while count <= 5:
print("Count is", count)
count = count + 1
print("Done")Output
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5 Done
Change it and run: change count <= 5 to count < 5. Which line disappears?
2.2The three parts of a while loop
count = 11 while count <= 52: print("Count is", count) count = count + 13
- 1Start: create the variable before the loop (
count = 1). - 2Condition: decide when to keep going (
count <= 5). - 3Update: change the variable inside the loop (
count = count + 1).
2.3The infinite loop (the classic danger)
If the condition never becomes False, the loop never stops:
count = 1
while count <= 5:
print("Count is", count)
# forgot to update count, so this runs forever!How to stop a runaway loop: in Jupyter, click the stop (square) button or use Kernel, then Interrupt. In a terminal, press Ctrl + C. Always double-check that something inside the loop moves it toward ending.
2.4When you don't know how many times
while is the right tool when the number of repeats isn't known in advance. How many times must you double 1 before it passes 1000?
amount = 1
steps = 0
while amount <= 1000:
amount = amount * 2
steps = steps + 1
print(amount, "after", steps, "doublings")Output
1024 after 10 doublings
Change it and run: change 1000 to 1000000. How many doublings now?
2.5Repeat until the user gives a valid answer
password = ""
while password != "python123":
password = input("Enter the password: ")
print("Access granted")Output
Enter the password: hello Enter the password: abc Enter the password: python123 Access granted
Change it and run: type your own guesses in the input box, one per line, and put python123 last.
The output above is a sample run: two wrong passwords, then the right one.
2.6while True with break
Sometimes it is clearer to loop "forever" and stop from inside with break (explained in Part 3):
n = 1
while True:
if n * n > 200:
break
n = n + 1
print("First n whose square is above 200:", n)Output
First n whose square is above 200: 15
2.7for vs while (the differences)
| for loop | while loop | |
|---|---|---|
| Repeats | a fixed, known number of times | as long as a condition is True |
| Best when | you know how many times (or have a range) | you don't know how many times |
| Counter | handled automatically by range() | you create and update it yourself |
| Risk of infinite loop | very low | high, if you forget the update |
| Typical use | counting, going through every character | waiting for something, repeating until valid, digit processing |
| Length of code | usually shorter | usually a bit longer |
The same task both ways (print 1 to 5):
# for version
for i in range(1, 6):
print(i)Output
1 2 3 4 5
# while version
i = 1
while i <= 5:
print(i)
i = i + 1Output
1 2 3 4 5
How to choose:
- "Do this 10 times" or "for each number from 1 to 100" means
for. - "Keep doing this until something happens" or "while the number is bigger than 0" means
while.
Every for loop can be rewritten as a while loop, but not always the other way around in a simple form.
Try it yourself
while loop.Show a hint
Show the solution
term = 1
count = 0
while count < 15:
print(term, end=" ")
term = term + 3
count = count + 1
print()Output
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43
3break, continue, loop else, nested loops and patterns
3.1break: stop the loop immediately
for number in range(101, 200):
if number % 13 == 0:
print("First multiple of 13 above 100:", number)
breakOutput
First multiple of 13 above 100: 104
Change it and run: change 13 to 17 in both places.
Without break, the loop would keep going to 199. With it, we leave as soon as we find the answer.
3.2continue: skip to the next iteration
continue skips the rest of the current iteration and jumps to the next one.
for number in range(1, 10):
if number % 2 == 0:
continue
print(number)Output
1 3 5 7 9
Even numbers are skipped, so only odd numbers print.
The same loop with break, with continue, and with neither.
for number in range(1, 10):
if number == 5:
break
print(number, end=" ")- 1printed
- 2printed
- 3printed
- 4printed
- 5loop stops
- 6never reached
- 7never reached
- 8never reached
- 9never reached
Output
1 2 3 4
break leaves the loop immediately: 5 is not printed, and the numbers after it are never reached.
3.3else on a loop (a Python special)
A loop can have an else block. It runs only if the loop finished without hitting break.
number = 7
for divisor in range(2, number):
if number % divisor == 0:
print(number, "is not prime")
break
else:
print(number, "is prime")Output
7 is prime
If a divisor had been found, break would skip the else part. Here is the same code with 9, which is divisible by 3:
number = 9
for divisor in range(2, number):
if number % divisor == 0:
print(number, "is not prime")
break
else:
print(number, "is prime")Output
9 is not prime
Change it and run: set number to 11, 15 and 13.
3.4pass
pass does nothing. It is a placeholder when Python needs a block but you have nothing to write yet.
for i in range(3):
pass # nothing to do yet
print("The loop ran, but did nothing.")Output
The loop ran, but did nothing.
3.5Nested loops (a loop inside a loop)
You can put one loop inside another. For each step of the outer loop, the inner loop runs completely.
for row in range(1, 4):
for column in range(1, 4):
print(row * column, end=" ")
print()Output
1 2 3 2 4 6 3 6 9
Change it and run: change both ranges to range(1, 6) to get a 5 by 5 table.
How it works:
row = 1: the inner loop runscolumn = 1, 2, 3, printing1 2 3. Thenprint()starts a new line.row = 2: the inner loop runs again, printing2 4 6.row = 3: printing3 6 9.
For each step of the outer loop, the inner loop runs completely.
for row in range(1, 4):
for column in range(1, 4):
print(row * column, end=" ")
print()Output so far
| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |
Press “Next step”. Watch row stay the same while column goes 1, 2, 3.
The inner body ran 3 x 3 = 9 times in total. Nested loops are used for tables, grids, and patterns.
runs = 0
for row in range(1, 4):
for column in range(1, 4):
runs = runs + 1
print("The inner body ran", runs, "times")Output
The inner body ran 9 times
3.6Common loop patterns
| Pattern | Idea | Example |
|---|---|---|
| Counter | count how many times something happens | count = count + 1 inside an if |
| Accumulator (sum) | add values together | total = total + i |
| Accumulator (product) | multiply values together (start at 1!) | result = result * i |
| Build text | add characters to a string | reversed_word = letter + reversed_word |
| Search | stop when found | if ...: ... break |
| Repeat until valid | keep asking | while answer != "yes": |
The counter pattern: how many numbers from 1 to 20 are divisible by 3?
count = 0
for number in range(1, 21):
if number % 3 == 0:
count = count + 1
print("Numbers divisible by 3:", count)Output
Numbers divisible by 3: 6
The product pattern. It must start at 1, because anything multiplied by 0 stays 0:
result = 1
for i in range(1, 6):
result = result * i
print("1 x 2 x 3 x 4 x 5 =", result)Output
1 x 2 x 3 x 4 x 5 = 120
Building text example (reversing a word):
word = "hello"
reversed_word = ""
for letter in word:
reversed_word = letter + reversed_word
print(reversed_word)Output
olleh
Change it and run: put your own word between the quotes.
Each new letter is placed in front of the previous result, so the word grows backwards.
Try it yourself
Show a hint
range(1, 101) and test number % 3 == 0 and number % 5 == 0.Show the solution
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print(number, end=" ")
print()Output
15 30 45 60 75 90
4Functions: what they are and how to write one
4.1What is a function?
A function is a named block of code that does one job. You write it once, then call it whenever you need it.
Real-life picture: a vending machine. You give it something (money and a choice), it does the work inside, and it gives something back (a snack). You don't need to know how it works inside.
You give it something
100
the argument
It does the work inside
add_tax(price)
price + price * 20 / 100
It gives something back
120.0
the return value
You already use functions:
| Function | What it does |
|---|---|
| print() | shows something on the screen |
| input() | asks the user for text |
| len("hello") | counts the characters in a text |
| abs(-5) | gives the positive value |
| round(3.14159, 2) | rounds a number |
| int("5") | converts text to a whole number |
| type(5) | tells the data type |
print(len("hello"))
print(abs(-5))
print(round(3.14159, 2))
print(int("5"))
print(type(5))Output
5 5 3.14 5 <class 'int'>
Now you will learn to write your own.
4.2Why use functions? (advantages over normal code)
Suppose a shop adds 20% tax to prices. Without a function you repeat the formula everywhere:
price1 = 100
price2 = 250
price3 = 80
total1 = price1 + price1 * 20 / 100
total2 = price2 + price2 * 20 / 100
total3 = price3 + price3 * 20 / 100
print(total1)
print(total2)
print(total3)Output
120.0 300.0 96.0
With a function you write the formula once:
def add_tax(price):
return price + price * 20 / 100
print(add_tax(100))
print(add_tax(250))
print(add_tax(80))Output
120.0 300.0 96.0
Change it and run: the tax becomes 18%: change 20 to 18. You edit one place, and all three results change.
| Advantage | What it means |
|---|---|
| Reuse | write once, use as many times as you want |
| Less repetition (DRY) | "Don't Repeat Yourself": fewer copy-pasted lines |
| Easy to change | if the tax becomes 18%, you edit one place, not 100 |
| Fewer mistakes | one tested formula instead of many copies that may differ |
| Readability | add_tax(100) tells you the intention; a raw formula doesn't |
| Easy testing | you can test a small function separately |
| Organization | a big program becomes small, named pieces |
| Teamwork | people can build different functions at the same time |
| Hiding details (abstraction) | users of the function don't need to know how it works inside |
4.3Defining and calling functions
def function_name():
# code of the function (indented)def1 say_hello2():3 print("Hello!")4
- 1
defis the keyword that defines a function. - 2Then the name.
- 3Parentheses
()and a colon:. - 4The body is indented by 4 spaces.
def say_hello():
print("Hello!")
print("Welcome to Python functions.")
say_hello()
say_hello()Output
Hello! Welcome to Python functions. Hello! Welcome to Python functions.
Change it and run: add a third call, or change a message. The change appears in every call.
4.4Defining is not running
defonly stores the instructions. Nothing happens yet.- The code inside runs only when you call the function with
name(). - You must define a function before you call it (higher in the file).
- The parentheses are required to call it.
say_helloalone does nothing.
Defined, but never called:
def say_hello():
print("Hello!")
print("The function is defined, but nobody called it.")Output
The function is defined, but nobody called it.
Called before it is defined:
say_hello()
def say_hello():
print("Hello!")Error
NameError: name 'say_hello' is not defined
Written without the parentheses:
def say_hello():
print("Hello!")
say_hello # no parentheses: the function is not called
print("Nothing was printed by say_hello.")Output
Nothing was printed by say_hello.
4.5What happens when you call a function
- Python reaches the call:
say_hello() - It jumps into the function and runs the body line by line
- When the body ends, it jumps back to just after the call
- The program continues
Follow the jump into the function and back
- 1def say_hello():
- 2 print("Hello!")
- 3
- 4print("Start")
- 5say_hello()
- 6print("End")
Output so far
Press “Next step” to start.
4.6Naming rules and style
- Same rules as variable names: letters, numbers, underscores, no spaces, not starting with a number.
- Use lowercase with underscores:
calculate_area, notCalculateArea. - Use verbs that describe the job:
add_tax,is_even,print_report.
4.7Docstrings (documenting a function)
A text in triple quotes as the first line of the body explains what the function does:
def add_tax(price):
"""Return the price plus 20% tax."""
return price + price * 20 / 100
print(add_tax(50))Output
60.0
You can read it later with help(add_tax).
Try it yourself
print_line() that prints a line of 20 dashes. Call it, print Report, then call it again.Show a hint
"-" * 20 repeats the dash 20 times. Define the function first, then use it twice.Show the solution
def print_line():
print("-" * 20)
print_line()
print("Report")
print_line()Output
-------------------- Report --------------------
5Parameters, arguments and return values
5.1Parameters and arguments
Functions become powerful when they can receive inputs.
| Term | Meaning | Example |
|---|---|---|
| Parameter | the variable name in the function definition | name in def greet(name): |
| Argument | the actual value you pass in when calling | "Aylin" in greet("Aylin") |
def greet(name):
print("Hello,", name)
greet("Aylin")
greet("Murad")Output
Hello, Aylin Hello, Murad
Change it and run: add a call with your own name.
5.2Several parameters
def rectangle_area(width, height):
return width * height
print(rectangle_area(5, 3))Output
15
5.3Positional vs. keyword arguments
- Positional: the values are matched by position. Order matters.
- Keyword: you write
parameter_name=value, so order does not matter.
def subtract(a, b):
return a - b
print(subtract(10, 3))
print(subtract(3, 10))
print(subtract(b=3, a=10))Output
7 -7 7
5.4Default values
You can give a parameter a default that is used when the caller doesn't provide one:
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")
greet("Aylin")
greet("Aylin", "Good morning")Output
Hello, Aylin! Good morning, Aylin!
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(5, 3))Output
25 125
Change it and run: add print(power(2, 10)).
Rule: parameters with defaults must come after those without defaults. def f(a=1, b): causes a SyntaxError:
def f(a=1, b):
return a + bError
SyntaxError: parameter without a default follows parameter with a default
5.5Wrong number of arguments
def rectangle_area(width, height):
return width * height
rectangle_area(5)Error
TypeError: rectangle_area() missing 1 required positional argument: 'height'
5.6Arguments can be variables or expressions
def double(n):
return n * 2
x = 7
print(double(x))
print(double(x + 3))
print(double(double(2)))Output
14 20 8
def add(a, b):
return a + b
print(add("5", 3))Error
TypeError: can only concatenate str (not "int") to str
5.7return sends a result back
def add(a, b):
return a + b
result = add(2, 3)
print(result)
print(add(10, 20) * 2)Output
5 60
The call add(2, 3) is replaced by its returned value (5), so you can store it in a variable or use it inside bigger expressions.
5.8print vs. return (a very important difference)
| print() | return | |
|---|---|---|
| Purpose | shows something to the human | gives a value back to the program |
| Can the result be reused? | no | yes (store it, calculate with it) |
| Ends the function? | no | yes |
def show_double(n):
print(n * 2) # only displays
def get_double(n):
return n * 2 # gives the value back
a = show_double(4) # prints 8, but a receives nothing useful
b = get_double(4) # prints nothing, b receives 8
print("a is", a)
print("b is", b)Output
8 a is None b is 8
A function without return gives back None. None is Python's "nothing here" value. That is why a above is None.
5.9return ends the function immediately
Lines after return are never executed:
def test():
print("Before return")
return 1
print("After return (never runs)")
print(test())Output
Before return 1
5.10Several return statements
A function can return from different places, often together with if:
def sign(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
return "zero"
print(sign(5))
print(sign(-2))
print(sign(0))Output
positive negative zero
5.11Functions that return True or False
Functions that answer a yes/no question are very useful inside if and loops:
def is_adult(age):
return age >= 18
if is_adult(20):
print("Welcome!")Output
Welcome!
Change it and run: call is_adult(15) instead. Nothing is printed.
5.12Functions can call other functions
def square(n):
return n * n
def sum_of_squares(a, b):
return square(a) + square(b)
print(sum_of_squares(3, 4))Output
25
Try it yourself
average_of_three(a, b, c) that returns the average. Print the average of 6, 7 and 11, then of 10, 20 and 30.Show a hint
return, then print the result of each call.Show the solution
def average_of_three(a, b, c):
return (a + b + c) / 3
print(average_of_three(6, 7, 11))
print(average_of_three(10, 20, 30))Output
8.0 20.0
6Lambda functions: a small function in one line
6.1What is a lambda function?
A lambda is a small function written in one line, without def and without a name. It takes parameters and gives back the value of one expression. Here is the same function written both ways:
def double(n):
return n * 2
double_short = lambda n: n * 2
print(double(5))
print(double_short(5))Output
10 10
Change it and run: change n * 2 to n * 3 in the lambda only. The two results are now different.
Both are called in the same way, with parentheses and an argument. The only difference is how they are written.
6.2Syntax
lambda parameters: expressionWith def: two lines and a name
def double(n): return n * 2
With lambda: one line, no name
lambda1 n2:3 n * 24
- 1The keyword
lambdastarts the function. It replacesdefand the name. - 2The parameters, without parentheses. Several are separated by commas.
- 3A colon.
- 4One expression. Its value is returned automatically: you do not write
return.
6.3Parameters: none, one, several, with a default
Everything you learned about parameters in Part 5 works here too:
add = lambda a, b: a + b
print(add(2, 3))
greeting = lambda: "Hello!"
print(greeting())
power = lambda base, exponent=2: base ** exponent
print(power(5))
print(power(5, 3))Output
5 Hello! 25 125
Change it and run: add a third parameter to add and call it with three numbers.
6.4A lambda that decides
A lambda has room for one expression only, so an if block does not fit. The one-line if/else from the last lesson is an expression, so it does:
parity = lambda n: "even" if n % 2 == 0 else "odd"
print(parity(7))
print(parity(10))
larger = lambda a, b: a if a > b else b
print(larger(12, 45))Output
odd even 45
Change it and run: write a lambda smaller that returns the smaller of two numbers.
6.5A lambda is a value
A lambda creates a function, and a function is a value like a number or a text. You can store it in a variable, and you can even use it at once without giving it a name. That is why a lambda is also called an anonymous function (a function without a name).
square = lambda n: n * n
print(type(square))
print(square(4))
print((lambda n: n * n)(4))Output
<class 'function'> 16 16
6.6def vs. lambda (the differences)
| def function | lambda | |
|---|---|---|
| Name | always has a name | no name (it can be stored in a variable) |
| Length | one or many lines | always one line |
| Body | any code: several steps, loops, if blocks | one expression only |
return | you write it | automatic: the value of the expression is returned |
| Docstring | yes | no |
| Best for | a job with several steps, or one that you reuse | a tiny job used once, usually given to another function |
Writing return inside a lambda is an error, because return is a statement, not an expression:
square = lambda n: return n * nError
SyntaxError: invalid syntax
6.7Where lambdas are really used: as an argument
A function can receive another function as an argument. In Part 4 you saw that a function name without parentheses does not call the function: it is the function itself. That is exactly what we pass.
def apply_twice(function, value):
return function(function(value))
def add_ten(n):
return n + 10
print(apply_twice(add_ten, 5))
print(apply_twice(lambda n: n * 2, 5))
print(apply_twice(lambda text: text + "!", "Hi"))Output
25 20 Hi!!
Change it and run: pass lambda n: n - 1 and predict the result before you run it.
add_ten needed two extra lines and a name. The lambda is written right where it is used. This is the real job of a lambda: a small rule that you hand to another function.
Several built-in functions accept such a rule. max and min take a key: a function that says what to compare.
print(max(-7, 3, 5))
print(max(-7, 3, 5, key=abs))
print(max(-7, 3, 5, key=lambda n: n * n))
print(min("pear", "fig", "banana", key=len))
print(max("pear", "fig", "banana", key=lambda word: word.count("a")))Output
5 -7 -7 fig banana
Change it and run: change the last line so that it finds the word with the most letters e.
key=abscompares the numbers without their sign, so-7wins.key=lencompares the lengths of the words, somingives the shortest word.- When no ready function exists for your rule, a lambda writes it on the spot.
6.8When not to use a lambda
- The job needs more than one step, a loop, or several decisions: write
def. - You reuse the function in many places: give it a proper name with
def. (Storing a lambda in a variable, as in the examples above, is good for learning. In real programs, Python's style guide recommendsdeffor that.) - The line becomes hard to read. Short code is good only while it stays clear.
def describe(score):
if score >= 90:
return "excellent"
elif score >= 50:
return "pass"
return "fail"
describe_short = lambda score: "excellent" if score >= 90 else "pass" if score >= 50 else "fail"
print(describe(95), describe(60), describe(30))
print(describe_short(95), describe_short(60), describe_short(30))Output
excellent pass fail excellent pass fail
Both give the same answers. The first one is easier to read, to test and to change.
Try it yourself
area takes a width and a height and returns the area of the rectangle. grade takes a score and returns "pass" when it is 50 or more, otherwise "fail". The three print lines are already written.Show a hint
name = lambda parameters: expression. For grade, use the one-line if/else: value_if_true if condition else value_if_false.Show the solution
area = lambda width, height: width * height
grade = lambda score: "pass" if score >= 50 else "fail"
print(area(4, 5))
print(grade(72))
print(grade(35))Output
20 pass fail
7Scope: where a variable lives
Scope means the part of the program where a variable can be used.
7.1Local scope
A variable created inside a function is local. It exists only while the function runs and cannot be used outside.
def show():
message = "I am local"
print(message)
show()Output
I am local
Using it outside the function fails:
def show():
message = "I am local"
print(message)
show()
print(message)Output
I am local
Error
NameError: name 'message' is not defined
Parameters are also local variables of the function.
7.2Global scope
A variable created outside all functions is global. A function can read it:
tax_rate = 20
def add_tax(price):
return price + price * tax_rate / 100
print(add_tax(50))Output
60.0
7.3Same name, different variables
A variable assigned inside a function is a new local one, even if a global one has the same name. The global one is not changed:
x = 10
def change():
x = 99
print("inside:", x)
change()
print("outside:", x)Output
inside: 99 outside: 10
Global scope: the whole program
the global x
Local scope: inside change(), only while it runs
a new, local x
x = 99 inside the function fills the local box. The global box still holds 10, and the local box disappears when the function ends.Likewise, a parameter name doesn't affect a global variable with the same name:
def double(n):
return n * 2
n = 100
print(double(5))
print(n)Output
10 100
7.4Changing a global variable (the global keyword)
To modify a global variable inside a function, you must declare it with global:
count = 0
def increase():
global count
count = count + 1
increase()
increase()
print(count)Output
2
Without the global line, Python treats count as local and raises an UnboundLocalError:
count = 0
def increase():
count = count + 1
increase()Error
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
7.5The better way: pass in, return out
Using global makes programs harder to understand because functions secretly change things. Prefer sending values in as parameters and getting results out with return:
def increase(count):
return count + 1
count = 0
count = increase(count)
count = increase(count)
print(count)Output
2
7.6Variables die when the function ends
Local variables are created when the function is called and destroyed when it returns. Calling the function again starts fresh.
def count_once():
counter = 0
counter = counter + 1
print("counter is", counter)
count_once()
count_once()Output
counter is 1 counter is 1
7.7Loops do not create a new scope
Unlike functions, a for or while loop does not have its own scope:
for i in range(3):
pass
print(i)Output
2
7.8Local vs. global summary
| Local variable | Global variable | |
|---|---|---|
| Created | inside a function | outside all functions |
| Usable | only inside that function | everywhere (can be read in functions) |
| Lifetime | until the function ends | until the program ends |
| Changing inside a function | free | needs the global keyword (avoid it) |
7.9Loops vs. functions vs. normal code
These tools solve different problems, and they work best together.
| Normal code | Loop | Function | |
|---|---|---|---|
| Runs | once, top to bottom | many times in place | each time it is called |
| Main purpose | one-time steps | repeat actions | package a job for reuse |
| Reuse in other places | copy and paste | copy and paste | just call it |
| Takes inputs | no | no | yes (parameters) |
| Gives a result back | no | no | yes (return) |
| Example | x = 5 | for i in range(5): | def add_tax(price): |
Combining them:
- A function can contain a loop (
factorial(n)uses a loop inside). - A loop can call a function (call
is_prime(n)for every number in a range).
Both at once: the function below has a loop inside, and the loop at the bottom calls the function.
def is_prime(n):
if n < 2:
return False
for divisor in range(2, n):
if n % divisor == 0:
return False
return True
for number in range(1, 11):
if is_prime(number):
print(number, "is prime")Output
2 is prime 3 is prime 5 is prime 7 is prime
Try it yourself
add_bonus(score, bonus) that returns the score plus the bonus, without global. With score = 70, store the result of add_bonus(score, 5) in new_score, then print Old score: 70 and New score: 75.Show a hint
return score + bonus. The global score stays 70 because you never assign to it.Show the solution
def add_bonus(score, bonus):
return score + bonus
score = 70
new_score = add_bonus(score, 5)
print("Old score:", score)
print("New score:", new_score)Output
Old score: 70 New score: 75
8Recursion: a function that calls itself
8.1The idea
Recursion means a function solves a problem by calling itself on a smaller version of the same problem. Think of Russian nesting dolls: to open the biggest doll you open the next one inside, and so on, until you reach the smallest.
Every recursive function needs two parts:
- Base case: the simplest situation where the answer is known, so the function stops.
- Recursive case: the function calls itself with a smaller input, moving toward the base case.
def countdown(n):
if n == 0: # base case
print("Liftoff!")
else:
print(n)
countdown(n - 1) # recursive case
countdown(3)Output
3 2 1 Liftoff!
Change it and run: call countdown(5).
8.2How recursion runs (the call stack)
For factorial(3) where factorial(n) = n * factorial(n - 1):
factorial(3) waits for 3 * factorial(2)
factorial(2) waits for 2 * factorial(1)
factorial(1) returns 1 (base case)
factorial(2) returns 2 * 1 = 2
factorial(3) returns 3 * 2 = 6Python remembers each waiting call on a "stack", then finishes them in reverse order.
The call stack of factorial(3), step by step.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(3))Calls that are open now (the newest is at the bottom)
- factorial(3) waits for 3 * factorial(2)
factorial(3) is called. 3 is not the base case, so it needs factorial(2) first and waits.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(3))Output
6
Change it and run: print factorial(5). It unfolds as 5 * 4 * 3 * 2 * 1.
8.3What if there is no base case?
def forever(n):
return forever(n + 1)
forever(1)Error
RecursionError: maximum recursion depth exceeded
Python stops you after about 1000 nested calls. Always make sure the input gets smaller and a base case exists.
8.4Recursion vs. loops
| Loop version | Recursive version | |
|---|---|---|
| Idea | repeat steps with a counter | solve a smaller copy of the problem |
| Code length | usually longer | often shorter and closer to the math definition |
| Speed and memory | fast, little memory | slower, uses extra memory for every call |
| Risk | infinite loop | RecursionError (too deep) |
| Best for | simple counting and repeating | problems that naturally contain smaller copies of themselves |
A warning about recursive Fibonacci: it recalculates the same values again and again. Here we count how many function calls it makes (this also shows global in action):
calls = 0
def fib(n):
global calls
calls = calls + 1
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20))
print("Function calls:", calls)Output
6765 Function calls: 21891
Change it and run: change 20 to 10, then to 25. Watch how fast the number of calls grows.
Work needed to find the 20th Fibonacci number
Finding the 20th Fibonacci number needs 21,891 calls. The loop version does the same job with only 20 steps. That is why loops are often better for simple repeated work.
Try it yourself
multiply(a, b) that multiplies using only addition: 4 times 3 is 4 plus (4 times 2). Print multiply(4, 3), multiply(7, 0) and multiply(5, 6).Show a hint
a + multiply(a, b - 1), so b gets smaller in every call.Show the solution
def multiply(a, b):
if b == 0: # base case
return 0
return a + multiply(a, b - 1) # recursive case
print(multiply(4, 3))
print(multiply(7, 0))
print(multiply(5, 6))Output
12 0 30
9How to approach problems with loops and functions
- Understand the problem. Write what goes in (inputs) and what must come out (result).
- Try a small example by hand. For "sum of digits of 1234", work it out on paper and notice the steps.
- Choose the tool. Known number of repeats means
for. Unknown meanswhile. A reusable job means a function. - Plan the loop. What is the starting value? What is the condition? What changes each time?
- Write the code and trace it with a small input using a trace table.
- Test edge cases:
0,1, negative numbers, very big numbers.
Try it yourself
10 km = 6.21 miles, with the miles rounded to 2 decimal places.Show a hint
for loop with range(10, 101, 10) makes the table. round(x, 2) rounds.Show the solution
def km_to_miles(km):
return km * 0.621371
for km in range(10, 101, 10):
print(km, "km =", round(km_to_miles(km), 2), "miles")Output
10 km = 6.21 miles 20 km = 12.43 miles 30 km = 18.64 miles 40 km = 24.85 miles 50 km = 31.07 miles 60 km = 37.28 miles 70 km = 43.5 miles 80 km = 49.71 miles 90 km = 55.92 miles 100 km = 62.14 miles
10Common mistakes
The red text is the real message Python shows. Where there is no message, the program runs but gives a wrong answer, which is harder to notice: the comment shows what it prints.
10.1Loop mistakes
Off-by-one with range
Wrong
for number in range(1, 10):
print(number, end=" ")
print()
# prints: 1 2 3 4 5 6 7 8 9Right
for number in range(1, 11):
print(number, end=" ")
print()
# prints: 1 2 3 4 5 6 7 8 9 10range(1, 10) stops at 9. Use range(1, 11) to include 10.
Forgetting the update in while
Wrong
count = 1
while count <= 5:
print("Count is", count)
# forgot to update count, so this runs forever!Right
count = 1
while count <= 5:
print("Count is", count)
count = count + 1
print("Done")An infinite loop. Change the variable inside the loop.
Resetting the accumulator inside the loop
Wrong
for i in range(1, 6):
total = 0
total = total + i
print("Total:", total)
# prints: Total: 5Right
total = 0
for i in range(1, 6):
total = total + i
print("Total:", total)
# prints: Total: 15total = 0 placed in the loop erases the progress. Create it before the loop.
Starting a product at 0
Wrong
result = 0
for i in range(1, 6):
result = result * i
print(result)
# prints: 0Right
result = 1
for i in range(1, 6):
result = result * i
print("1 x 2 x 3 x 4 x 5 =", result)
# prints: 1 x 2 x 3 x 4 x 5 = 120Everything becomes 0. Start multiplication at 1.
Wrong indentation
Wrong
total = 0
for i in range(1, 4):
total = total + i
print("Total:", total)
# prints the total 3 timesRight
total = 0
for i in range(1, 4):
total = total + i
print("Total:", total)
# prints: Total: 6Code runs at the wrong time or not at all. Indent the loop body by 4 spaces, and nothing else.
Using range() with decimals
Wrong
for x in range(0, 1, 0.1):
print(x)TypeError: 'float' object cannot be interpreted as an integer
Right
for x in range(0, 10):
print(x / 10)range() only accepts whole numbers.
Forgetting int() for input
Wrong
n = input("How many times? ")
for i in range(n):
print("Hello")TypeError: 'str' object cannot be interpreted as an integer
Right
n = int(input("How many times? "))
for i in range(n):
print("Hello")Text used as a number.
Wrong condition direction
Wrong
n = 3
while n < 0:
print(n)
n = n - 1
print("Done")
# prints: DoneRight
n = 3
while n > 0:
print(n)
n = n - 1
print("Done")
# prints: 3, 2, 1, Donewhile n < 0 when you meant > 0: the loop never starts. Trace with a small example.
10.2Function mistakes
Forgetting the colon after def ...()
Wrong
def say_hello()
print("Hello!")SyntaxError: expected ':'
Right
def say_hello():
print("Hello!")Add : at the end of the def line.
Calling before defining
Wrong
say_hello()
def say_hello():
print("Hello!")NameError: name 'say_hello' is not defined
Right
def say_hello():
print("Hello!")
say_hello()Define the function higher in the file.
Forgetting the parentheses on a call
Wrong
say_hello # does nothing
Right
say_hello() # calls the function
Write say_hello().
Using print instead of return
Wrong
def add(a, b):
print(a + b)
result = add(2, 3)
print("result is", result)
# prints: 5, then result is NoneRight
def add(a, b):
return a + b
result = add(2, 3)
print("result is", result)
# prints: result is 5The result can't be reused (you get None). return the value.
Wrong number of arguments
Wrong
def rectangle_area(width, height):
return width * height
rectangle_area(5)TypeError: rectangle_area() missing 1 required positional argument: 'height'
Right
def rectangle_area(width, height):
return width * height
rectangle_area(5, 3)Match the parameters.
Using a local variable outside the function
Wrong
def show():
message = "I am local"
print(message)
show()
print(message)NameError: name 'message' is not defined
Right
def show():
message = "I am local"
return message
print(show())Return it, or define it outside.
Putting code after return
Wrong
def test():
return 1
print("never runs")Right
def test():
print("runs")
return 1It never runs. Place return last.
Recursion with no base case
Wrong
def forever(n):
return forever(n + 1)
forever(1)RecursionError: maximum recursion depth exceeded
Right
def countdown(n):
if n == 0: # base case
return
countdown(n - 1) # smaller inputAdd a base case and shrink the input.
Writing return inside a lambda
Wrong
square = lambda n: return n * n
SyntaxError: invalid syntax
Right
square = lambda n: n * n
A lambda returns its expression by itself. Leave return out.
Calling a function while passing it
Wrong
def apply_twice(function, value):
return function(function(value))
def add_ten(n):
return n + 10
print(apply_twice(add_ten(5), 5))TypeError: 'int' object is not callable
Right
def apply_twice(function, value):
return function(function(value))
def add_ten(n):
return n + 10
print(apply_twice(add_ten, 5))add_ten(5) is the number 15, not a function. Pass the name without parentheses: add_ten.
Overusing global
Wrong
count = 0
def increase():
global count
count = count + 1Right
def increase(count):
return count + 1
count = 0
count = increase(count)Confusing, bug-prone code. Use parameters and return.
11Solved problems (easy to medium-hard)
Every example was run, and the outputs are real. Each one shows the problem, the code, the output, and why it works. Press Edit and run and try the changes suggested under the code.
11.1Level 1: Easy
Problem 1: Print the numbers 1 to 5
for number in range(1, 6):
print(number)Output
1 2 3 4 5
While version:
number = 1
while number <= 5:
print(number)
number = number + 1Output
1 2 3 4 5
Why: range(1, 6) stops before 6. In the while version we create, test, and update the counter ourselves.
Problem 2: Sum of the numbers from 1 to n
n = 10
total = 0
for i in range(1, n + 1):
total = total + i
print("Sum of 1 to", n, "is", total)Output
Sum of 1 to 10 is 55
Change it and run: set n to 100. The answer is 5050.
While version:
n = 10
total = 0
i = 1
while i <= n:
total = total + i
i = i + 1
print("Sum of 1 to", n, "is", total)Output
Sum of 1 to 10 is 55
Why: the accumulator starts at 0 and grows. (A shortcut formula also exists: n * (n + 1) // 2 gives 55.)
Problem 3: Countdown
count = 5
while count >= 1:
print(count)
count = count - 1
print("Liftoff!")Output
5 4 3 2 1 Liftoff!
For version (counting down with a negative step):
for count in range(5, 0, -1):
print(count)
print("Liftoff!")Output
5 4 3 2 1 Liftoff!
Problem 4: Multiplication table of 7
for i in range(1, 11):
print("7 x", i, "=", 7 * i)Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Change it and run: make it the table of 9: change both 7s.
Why: the loop variable i changes from 1 to 10 and is used in every line.
Problem 5: Sum of the even numbers from 1 to 20
total = 0
for number in range(2, 21, 2):
total = total + number
print("Sum of even numbers:", total)Output
Sum of even numbers: 110
Alternative with if:
total = 0
for number in range(1, 21):
if number % 2 == 0:
total = total + number
print("Sum of even numbers:", total)Output
Sum of even numbers: 110
Why: the first version uses a step of 2 so it never visits odd numbers. The second visits all numbers and filters them with if.
Problem 6: Count the vowels in a word
word = "programming"
vowel_count = 0
for letter in word:
if letter in "aeiou":
vowel_count = vowel_count + 1
print("Vowels in", word, ":", vowel_count)Output
Vowels in programming : 3
Change it and run: try your own word.
Why: letter in "aeiou" checks whether the letter appears inside the text "aeiou". This is the counter pattern.
Problem 7: A function with two parameters
def introduce(name, age):
print("My name is", name, "and I am", age, "years old.")
introduce("Aylin", 20)
introduce("Murad", 25)Output
My name is Aylin and I am 20 years old. My name is Murad and I am 25 years old.
Why: the function does the printing, and each call supplies different arguments.
Problem 8: Square and cube
def square(n):
return n * n
def cube(n):
return n * n * n
print(square(6))
print(cube(3))
print(square(4) + cube(2))Output
36 27 24
Why: because the functions return values, we can combine them in a calculation.
Problem 9: Even checker and the larger of two numbers
def is_even(number):
return number % 2 == 0
def larger(a, b):
if a > b:
return a
return b
print(is_even(10))
print(is_even(7))
print(larger(12, 45))Output
True False 45
Why: is_even returns a Boolean directly. In larger, the second return only runs when the if was not true, so no else is needed.
11.2Level 2: Medium
Problem 10: Factorial (loop version and recursion version)
The factorial of n (written n!) is 1 x 2 x 3 x ... x n. For example 5! = 120. By definition, 0! = 1.
Loop version:
def factorial_loop(n):
result = 1
for i in range(2, n + 1):
result = result * i
return result
print(factorial_loop(5))
print(factorial_loop(0))
print(factorial_loop(10))Output
120 1 3628800
Recursive version:
def factorial_recursive(n):
if n <= 1: # base case
return 1
return n * factorial_recursive(n - 1) # recursive case
print(factorial_recursive(5))
print(factorial_recursive(0))Output
120 1
Why: the loop multiplies as it goes (the product starts at 1). The recursive version follows the definition n! = n x (n-1)!, and stops at the base case. For 5! the calls unfold like this: 5 * 4 * 3 * 2 * 1.
Problem 11: Power without using **
def power(base, exponent):
result = 1
for _ in range(exponent):
result = result * base
return result
print(power(2, 10))
print(power(5, 0))
print(power(3, 4))Output
1024 1 81
Why: multiplying base by itself exponent times. We use _ because we don't need the loop variable.
Problem 12: Fibonacci numbers (loop and recursion)
The Fibonacci sequence starts 0, 1, and every next number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, ...
Print the first 10 terms:
a = 0
b = 1
for _ in range(10):
print(a, end=" ")
next_value = a + b
a = b
b = next_value
print()Output
0 1 1 2 3 5 8 13 21 34
A function that returns the n-th term (loop version):
def fibonacci_loop(n):
a = 0
b = 1
for _ in range(n):
next_value = a + b
a = b
b = next_value
return a
print(fibonacci_loop(10))
print(fibonacci_loop(50))Output
55 12586269025
Recursive version:
def fibonacci_recursive(n):
if n <= 1: # base cases: fib(0)=0, fib(1)=1
return n
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
print(fibonacci_recursive(10))Output
55
Why: the recursive code reads exactly like the definition, but it is very slow for big inputs (see Part 8). The loop version keeps only the last two values and is instant, even for n = 50.
Problem 13: Sum of the digits of a number
For 1234 the answer is 1 + 2 + 3 + 4 = 10.
number = 1234
total = 0
while number > 0:
digit = number % 10 # last digit
total = total + digit
number = number // 10 # remove the last digit
print("Sum of digits:", total)Output
Sum of digits: 10
Change it and run: set number to 98765. The sum is 35.
Trace table:
| number at the start | digit | total | number after // 10 |
|---|---|---|---|
| 1234 | 4 | 4 | 123 |
| 123 | 3 | 7 | 12 |
| 12 | 2 | 9 | 1 |
| 1 | 1 | 10 | 0 (loop ends) |
As a function (loop version and recursive version):
def sum_of_digits(n):
total = 0
while n > 0:
total = total + n % 10
n = n // 10
return total
def sum_of_digits_recursive(n):
if n < 10: # base case: a single digit
return n
return n % 10 + sum_of_digits_recursive(n // 10)
print(sum_of_digits(98765))
print(sum_of_digits_recursive(98765))Output
35 35
Why: % 10 gives the last digit and // 10 removes it. This is the standard trick for working with digits using while.
Problem 14: Count the digits and reverse a number
def count_digits(n):
if n == 0:
return 1
count = 0
while n > 0:
count = count + 1
n = n // 10
return count
def reverse_number(n):
reversed_n = 0
while n > 0:
digit = n % 10
reversed_n = reversed_n * 10 + digit
n = n // 10
return reversed_n
print(count_digits(98765))
print(count_digits(0))
print(reverse_number(1234))
print(reverse_number(1200))Output
5 1 4321 21
Why: to reverse, we take the last digit of n and attach it to the end of reversed_n (multiply by 10, then add). 1200 becomes 21 because a number cannot keep leading zeros.
Problem 15: Palindromes (numbers and text)
A palindrome reads the same forwards and backwards (121, "level").
Palindrome number:
def reverse_number(n):
reversed_n = 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n = n // 10
return reversed_n
def is_palindrome_number(n):
return n == reverse_number(n)
print(is_palindrome_number(121))
print(is_palindrome_number(123))
print(is_palindrome_number(1221))Output
True False True
Palindrome text:
def is_palindrome_text(text):
text = text.lower()
reversed_text = ""
for letter in text:
reversed_text = letter + reversed_text
return text == reversed_text
print(is_palindrome_text("Level"))
print(is_palindrome_text("Python"))
print(is_palindrome_text("Racecar"))Output
True False True
Why: both build the reversed version and compare it with the original. For text we use .lower() first so that capital letters don't matter. (This simple version doesn't handle spaces or punctuation.)
Problem 16: Prime number checker
A prime number is greater than 1 and divisible only by 1 and itself.
def is_prime(n):
if n < 2:
return False
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
return False
divisor = divisor + 1
return True
print(is_prime(17))
print(is_prime(18))
print(is_prime(1))
print(is_prime(2))Output
True False False True
Print all primes up to 30:
def is_prime(n):
if n < 2:
return False
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
return False
divisor = divisor + 1
return True
for number in range(2, 31):
if is_prime(number):
print(number, end=" ")
print()Output
2 3 5 7 11 13 17 19 23 29
Why: we only need to test divisors up to the square root of n (that is why the condition is divisor * divisor <= n). If any divisor works, we return False immediately. If none works, the number is prime. The final loop shows how a loop can call a function.
Problem 17: Temperature conversion table
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
for celsius in range(0, 101, 20):
print(celsius, "C =", celsius_to_fahrenheit(celsius), "F")Output
0 C = 32.0 F 20 C = 68.0 F 40 C = 104.0 F 60 C = 140.0 F 80 C = 176.0 F 100 C = 212.0 F
Change it and run: change the step from 20 to 10.
Why: the function holds the formula once, and the loop produces a whole table using a step of 20.
Problem 18: A grade function used inside a loop
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
for score in range(55, 100, 10):
print(score, "->", get_grade(score))Output
55 -> F 65 -> D 75 -> C 85 -> B 95 -> A
Why: if/elif/else inside a function with several return statements. Each return ends the function, so no extra else is needed after it.
Problem 19: A calculator function
def calculate(a, b, operator):
if operator == "+":
return a + b
elif operator == "-":
return a - b
elif operator == "*":
return a * b
elif operator == "/":
if b == 0:
return "Error: cannot divide by zero"
return a / b
else:
return "Unknown operator"
print(calculate(10, 5, "+"))
print(calculate(10, 4, "/"))
print(calculate(10, 0, "/"))
print(calculate(10, 5, "%"))Output
15 2.5 Error: cannot divide by zero Unknown operator
Why: the function combines everything from the if/else topic and makes it reusable with any numbers and operators.
11.3Level 3: Medium-Hard
Problem 20: Greatest common divisor (GCD) and least common multiple (LCM)
The GCD of 48 and 18 is 6, the biggest number that divides both.
Euclid's algorithm with a while loop:
def gcd(a, b):
while b != 0:
remainder = a % b
a = b
b = remainder
return a
def lcm(a, b):
return a * b // gcd(a, b)
print(gcd(48, 18))
print(lcm(4, 6))Output
6 12
Trace for gcd(48, 18):
| a | b | a % b |
|---|---|---|
| 48 | 18 | 12 |
| 18 | 12 | 6 |
| 12 | 6 | 0 |
| 6 | 0 | (stop, answer is 6) |
Recursive version:
def gcd_recursive(a, b):
if b == 0:
return a
return gcd_recursive(b, a % b)
print(gcd_recursive(48, 18))Output
6
Why: the key idea is that gcd(a, b) equals gcd(b, a % b). The loop and the recursion do exactly the same steps.
Problem 21: The Collatz sequence
Start with any positive whole number. If it is even, divide it by 2. If it is odd, multiply by 3 and add 1. Repeat until you reach 1. How many steps does it take?
def collatz_steps(n):
steps = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps = steps + 1
return steps
print(collatz_steps(6))
print(collatz_steps(27))Output
8 111
Why: we don't know in advance how many steps it will take, so while is the right choice. For 6 the path is 6, 3, 10, 5, 16, 8, 4, 2, 1, which is 8 steps.
Problem 22: Guessing a number by halving
A number between 1 and 100 is hidden. Always guess the middle of the remaining range. How many guesses does it take?
secret = 73
low = 1
high = 100
guesses = 0
while True:
middle = (low + high) // 2
guesses = guesses + 1
if middle == secret:
print("Found", secret, "in", guesses, "guesses")
break
elif middle < secret:
low = middle + 1
else:
high = middle - 1Output
Found 73 in 6 guesses
Change it and run: change the secret to 1, 100 or 50, and count the guesses.
Why: each guess throws away half of the possibilities. This idea (called binary search) can find any number from 1 to 100 in at most 7 guesses. It uses while True with break.
Problem 23: How many years until the money doubles?
You save 1000 at 5% yearly interest. After how many years do you have at least 2000?
balance = 1000
years = 0
while balance < 2000:
balance = balance * 105 / 100
years = years + 1
print("Money doubles after", years, "years")
print("Balance:", round(balance, 2))Output
Money doubles after 15 years Balance: 2078.93
Change it and run: change the interest: 105 to 110 is 10% a year.
Why: we don't know the number of years in advance. The loop runs while the goal is not reached.
Problem 24: Armstrong numbers
A 3-digit number is an Armstrong number if the sum of the cubes of its digits equals the number. Example: 153 = 1³ + 5³ + 3³.
def is_armstrong(n):
original = n
total = 0
while n > 0:
digit = n % 10
total = total + digit ** 3
n = n // 10
return total == original
for number in range(100, 1000):
if is_armstrong(number):
print(number, end=" ")
print()Output
153 370 371 407
Why: it combines a while loop (digit extraction) inside a function, called from a for loop that tests every 3-digit number. Note that we saved original first because n gets destroyed by the loop.
Problem 25: Perfect numbers
A number is perfect if it equals the sum of its divisors smaller than itself. Example: 6 = 1 + 2 + 3.
def sum_of_divisors(n):
total = 0
for i in range(1, n):
if n % i == 0:
total = total + i
return total
for number in range(2, 1001):
if sum_of_divisors(number) == number:
print(number, "is perfect")Output
6 is perfect 28 is perfect 496 is perfect
Why: this is a nested structure: the outer loop goes through the numbers, and each call of the function runs its own inner loop to add the divisors.
Problem 26: Convert a decimal number to binary
def to_binary(n):
if n == 0:
return "0"
binary = ""
while n > 0:
remainder = n % 2
binary = str(remainder) + binary
n = n // 2
return binary
print(to_binary(10))
print(to_binary(255))
print(to_binary(0))Output
1010 11111111 0
Why: repeatedly divide by 2 and collect the remainders. The last remainder is the first digit, so each new digit is placed in front (str(remainder) + binary).
Problem 27: Star patterns (nested loops and text repetition)
A right triangle:
rows = 5
for i in range(1, rows + 1):
print("*" * i)Output
* ** *** **** *****
Change it and run: change rows to 8.
A centered pyramid:
rows = 5
for i in range(1, rows + 1):
spaces = " " * (rows - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)Output
* *** ***** ******* *********
The right triangle again, the nested-loop way:
rows = 5
for i in range(1, rows + 1):
for _ in range(i):
print("*", end="")
print()Output
* ** *** **** *****
Why: "*" * i repeats the text i times. Row i of the pyramid needs rows - i spaces and 2 * i - 1 stars. The same result can be built with an inner loop that prints one star at a time, which is the nested-loop way.
Problem 28: Digital root
Keep adding the digits of a number until a single digit remains. 9875 gives 9 + 8 + 7 + 5 = 29, then 2 + 9 = 11, then 1 + 1 = 2.
def sum_of_digits(n):
total = 0
while n > 0:
total = total + n % 10
n = n // 10
return total
def digital_root(n):
while n >= 10:
n = sum_of_digits(n)
return n
print(digital_root(9875))
print(digital_root(5))Output
2 5
Why: a while loop in one function calls another function that has its own while loop. Splitting the work into two small functions keeps each one easy to understand.
Problem 29: A countdown with recursion and a loop
def countdown_recursive(n):
if n == 0:
return
print(n)
countdown_recursive(n - 1)
countdown_recursive(4)Output
4 3 2 1
def countdown_loop(n):
while n > 0:
print(n)
n = n - 1
countdown_loop(4)Output
4 3 2 1
Why: both functions do the same job. A bare return simply ends the function early (and gives back None). Comparing the two shows how recursion replaces the loop counter with a smaller input in each call.
Problem 30: Number of digits that are even, using a loop and a function
Count how many digits of a number are even. For 482915 the even digits are 4, 8, 2, so the answer is 3.
def is_even(number):
return number % 2 == 0
def count_even_digits(n):
count = 0
while n > 0:
digit = n % 10
if is_even(digit):
count = count + 1
n = n // 10
return count
print(count_even_digits(482915))
print(count_even_digits(13579))Output
3 0
Why: it brings together all three ideas of this topic: a while loop to extract the digits, an if to decide, and small functions that each do one job.
Problem 31: Count the numbers that pass a test (a function as an argument)
Write one function that counts how many numbers in a range pass a test. The test itself is given as a function, so the same loop can count even numbers, numbers divisible by 3 and 5, primes, or anything else.
def is_prime(n):
if n < 2:
return False
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
return False
divisor = divisor + 1
return True
def count_if(test, start, stop):
count = 0
for n in range(start, stop + 1):
if test(n):
count = count + 1
return count
print(count_if(lambda n: n % 2 == 0, 1, 20))
print(count_if(lambda n: n % 3 == 0 and n % 5 == 0, 1, 100))
print(count_if(is_prime, 1, 30))Output
10 6 10
Change it and run: count the numbers from 1 to 100 that end in 7 with lambda n: n % 10 == 7.
Why: the loop and the counter are written once, and the rule arrives as the parameter test. A short rule is a lambda written at the call. A longer rule such as is_prime is a def function, passed by its name without parentheses. In the next lesson, filter works in exactly this way.
12Practice problems (try them yourself)
Fifteen problems in three levels. Most of them ask for a function: write it above the lines that are already in the editor (they read the input and call your function). Press Run to try one input, then Check to run your code with several inputs, including the edge values 0 and 1.
Easy
One small function or one loop.
- 1.Write a function
cube_volume(side)that returns the volume of a cube. The volume is side × side × side.Examples:3gives271gives110gives1000Show a hint
The function needs one parameter and one line:return side * side * side. Return the value, do not print it inside the function.Show one possible solution
Pythondef cube_volume(side): return side * side * side side = int(input()) print(cube_volume(side))Output
27
- 2.Write a function
is_positive(n)that returnsTrueorFalse. Zero is not positive.Examples:5givesTrue-3givesFalse0givesFalseShow a hint
A comparison already givesTrueorFalse, so the body can be one line:return n > 0.Show one possible solution
Pythondef is_positive(n): return n > 0 n = int(input()) print(is_positive(n))Output
True
- 3.Count how many times the letter
"a"appears in a word. Read the word and print the count.Examples:bananagives3applegives1skygives0Show a hint
The counter pattern:count = 0before the loop, thenfor letter in word:and add 1 whenletter == "a". A capitalAis a different character.Show one possible solution
Pythonword = input() count = 0 for letter in word: if letter == "a": count = count + 1 print(count)Output
3
Medium
A loop inside a function, and the same job with recursion.
- 4.Write a function that returns the sum of all numbers from 1 to
n, using a loop. Then write it again using recursion. Name themsum_to(n)andsum_to_recursive(n).Examples:10gives55 551gives1 10gives0 0Show a hint
Loop: an accumulator that starts at 0. Recursion: the sum up tonisnplus the sum up ton - 1, and the base case isn <= 0, which returns 0.Show one possible solution
Pythondef sum_to(n): total = 0 for i in range(1, n + 1): total = total + i return total def sum_to_recursive(n): if n <= 0: # base case return 0 return n + sum_to_recursive(n - 1) # recursive case n = int(input()) print(sum_to(n), sum_to_recursive(n))Output
55 55
- 5.Write a function
count_digits(n)using awhileloop, then write a recursive version,count_digits_recursive(n). The number 0 has 1 digit.Examples:98765gives5 57gives1 10gives1 1Show a hint
Loop:n // 10removes the last digit; count how many times you can do it. Handle 0 before the loop. Recursion: a number below 10 has 1 digit; otherwise it is 1 plus the digits ofn // 10.Show one possible solution
Pythondef count_digits(n): if n == 0: return 1 count = 0 while n > 0: count = count + 1 n = n // 10 return count def count_digits_recursive(n): if n < 10: # base case: one digit return 1 return 1 + count_digits_recursive(n // 10) # recursive case n = int(input()) print(count_digits(n), count_digits_recursive(n))Output
5 5
- 6.Write a function
is_perfect_square(n)using a loop (do not use**0.5). It returnsTruefor 0, 1, 4, 9, 16 and so on.Examples:16givesTrue15givesFalse1givesTrueShow a hint
Tryi = 0, 1, 2, ...whilei * i <= n. Ifi * i == n, returnTrueat once. If the loop ends without a match, returnFalse.Show one possible solution
Pythondef is_perfect_square(n): i = 0 while i * i <= n: if i * i == n: return True i = i + 1 return False n = int(input()) print(is_perfect_square(n))Output
True
- 7.Write a function that checks whether a number is an Armstrong number with any number of digits:
is_armstrong(n). A number with d digits is an Armstrong number when the sum of its digits, each raised to the power d, equals the number. Example: 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴.Examples:153givesTrue9474givesTrue9475givesFalseShow a hint
First count the digits (a small helper function). Then use the digit trick% 10and// 10, and adddigit ** digitseach time. Save the original number before the loop destroys it.Show one possible solution
Pythondef count_digits(n): count = 0 while n > 0: count = count + 1 n = n // 10 return count def is_armstrong(n): digits = count_digits(n) original = n total = 0 while n > 0: total = total + (n % 10) ** digits n = n // 10 return total == original n = int(input()) print(is_armstrong(n))Output
True
Medium-Hard
Loops, conditions and functions working together.
- 8.Print all the prime numbers between 1 and 200 and count how many there are. Print the primes on one line separated by spaces, then
Count:and the number on the next line.Show a hint
Reuseis_prime(n)from solved problem 16. Loop overrange(1, 201), print each prime withend=" "and add 1 to a counter. An emptyprint()ends the line.Show one possible solution
Pythondef is_prime(n): if n < 2: return False divisor = 2 while divisor * divisor <= n: if n % divisor == 0: return False divisor = divisor + 1 return True count = 0 for number in range(1, 201): if is_prime(number): print(number, end=" ") count = count + 1 print() print("Count:", count)Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 Count: 46
- 9.Write
power_recursive(base, exponent)using recursion. The exponent is 0 or more.Examples:2, 10gives10245, 0gives13, 4gives81Show a hint
Base case: any number to the power 0 is 1. Recursive case:basetimes the power withexponent - 1.Show one possible solution
Pythondef power_recursive(base, exponent): if exponent == 0: # base case return 1 return base * power_recursive(base, exponent - 1) # recursive case base = int(input()) exponent = int(input()) print(power_recursive(base, exponent))Output
1024
- 10.Write a function that returns how many times you can divide a number by 2 before it becomes odd:
count_halvings(n), for a positive whole number. Example: 12, 6, 3 takes 2 divisions.Examples:8gives312gives27gives0Show a hint
You do not know the number of repeats in advance, so usewhile. The condition isn % 2 == 0; inside, divide with//and count.Show one possible solution
Pythondef count_halvings(n): count = 0 while n % 2 == 0: n = n // 2 count = count + 1 return count n = int(input()) print(count_halvings(n))Output
3
- 11.Write a function that finds the largest digit of a number:
largest_digit(n).Examples:482915gives97gives71000gives1Show a hint
Keep the best digit so far in a variable that starts at 0. Take the digits one by one with% 10and// 10, and replace the best one when a digit is larger.Show one possible solution
Pythondef largest_digit(n): largest = 0 while n > 0: digit = n % 10 if digit > largest: largest = digit n = n // 10 return largest n = int(input()) print(largest_digit(n))Output
9
- 12.Write a "number guessing game" with
while: the program has a secret number and asks the user until they guess correctly, giving "too high" or "too low" hints, and finally prints the number of attempts.Show a hint
Repeat until valid:while guess != secret:. Inside the loop read the guess withint(input(...)), add 1 to the attempts, then compare. To play here, type your guesses in the input box, one per line.Show one possible solution
Pythonsecret = 37 attempts = 0 guess = 0 while guess != secret: guess = int(input("Your guess: ")) attempts = attempts + 1 if guess > secret: print("Too high") elif guess < secret: print("Too low") print("Correct! Attempts:", attempts)Output
Your guess: 50 Too high Your guess: 25 Too low Your guess: 37 Correct! Attempts: 3
- 13.Print a diamond pattern of stars using loops. Use
rows = 4: the lines have 1, 3, 5, 7, 5, 3 and 1 stars, and each line is centered.Show a hint
The top half is the pyramid of solved problem 27. The bottom half is the same loop counting down:range(rows - 1, 0, -1).Show one possible solution
Pythonrows = 4 for i in range(1, rows + 1): print(" " * (rows - i) + "*" * (2 * i - 1)) for i in range(rows - 1, 0, -1): print(" " * (rows - i) + "*" * (2 * i - 1))Output
* *** ***** ******* ***** *** *
- 14.Write a function that returns
Trueif two numbers have exactly the same digits sum:same_digit_sum(a, b). Example: 123 and 60 both give 6.Examples:123, 321givesTrue123, 60givesTrue19, 28givesTrueShow a hint
Writesum_of_digits(n)first (solved problem 13), then compare the two results insidesame_digit_sum. One function calls the other.Show one possible solution
Pythondef sum_of_digits(n): total = 0 while n > 0: total = total + n % 10 n = n // 10 return total def same_digit_sum(a, b): return sum_of_digits(a) == sum_of_digits(b) a = int(input()) b = int(input()) print(same_digit_sum(a, b))Output
True
- 15.Write a function that calculates the sum of the series
1/1 + 1/2 + 1/3 + ... + 1/n:harmonic(n). The last line prints the result rounded to 3 decimal places.Examples:4gives2.0831gives1.02gives1.5Show a hint
An accumulator that starts at 0. Loopifrom 1 tonand add1 / ieach time.Show one possible solution
Pythondef harmonic(n): total = 0 for i in range(1, n + 1): total = total + 1 / i return total n = int(input()) print(round(harmonic(n), 3))Output
2.083
13Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
14Quick summary
| Concept | What it does | Example |
|---|---|---|
for loop | repeats a known number of times | for i in range(5): |
range(a, b, step) | produces numbers (stop is excluded) | range(1, 11) gives 1 to 10 |
while loop | repeats while a condition is True | while n > 0: |
| Infinite loop | a loop that never ends (forgot the update) | stop it with Ctrl + C or Interrupt |
break | leaves the loop immediately | if found: break |
continue | skips to the next iteration | if n % 2 == 0: continue |
| Nested loop | a loop inside a loop | tables and patterns |
| Accumulator | collects a result in a loop | total = total + i |
| Function | a named, reusable block of code | def add_tax(price): |
| Parameter / argument | input name / input value | def f(x) / f(5) |
| Default value | used when no argument is given | def f(x, y=2): |
return | sends a value back and ends the function | return a + b |
print vs return | show to the user vs give back to the program | return can be reused |
| Lambda | a small one-line function without a name | lambda n: n * 2 |
| Local variable | exists only inside the function | created in a function |
| Global variable | exists outside all functions | needs global to change inside |
| Recursion | a function calling itself with a smaller input | factorial(n - 1) |
| Base case | the stopping point of recursion | if n <= 1: return 1 |