Python
/
Functions
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 5
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Functions Recursion
It is legal for a function to call itself def f(n): if n <= 0: return f(n-1)Function
Recursion
p88 It is legal for a function to call itself (one of the most magical things a program can do).
# Recursion:
#
# A function can call himself
def countdown(n):
if n <= 0:
print ("Time!")
else:
print(n)
countdown(n-1)
countdown(3)
# 3
# 2
# 1
# Time!
Flow
What happens if we call this function like this?
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__
Repeat
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)
# abc
# abc
# abc
➥ Questions
Last update: 60 days ago