PROGRAMMING

# m9/ PYTHON REMEMBERS

Last update:   23-07-2021

### Recursion

p88 ! It is legal for a function to call itself It is one of the most magical things a program can do. What happens when we call countdown(3)?

def countdown(n):
if n <= 0:
print ("Time!")
else:
print(n)
countdown(n-1)

countdown(3)

# 3
# 2
# 1
# Time!
... 5 lines 

countdown executions begins with n=3 ...
since n is greater than 0 it outputs 3 ..
then it calls itself ...

countdown executions begins with n=2 ...
since n is greater than 0 it outputs 2 ..
then it calls itself ...

countdown executions begins with n=1 ...
since n is greater than 0 it outputs 1 ..
then it calls itself ...

countdown executions begins with n=0 ...
since n is not greater than 0 it outputs Time! ..
then returns ...

the countdown that got n=1 returns

the countdown that got n=2 returns

the countdown that got n=3 returns

After that we are back in the __main__
... 10 lines 
p89 ! As another example, we can print a string n times. It is easier to write a for loop, but there are times when we need recursion.

def repeat(s, n):
if n <=0 :
return
print(s)
repeat(s, n-1)

repeat('abc', 3)


Questions

A B C D E F
🔔
1/2