Recursive Functions Part 2
Part of the Logic & Flow section of Coddy's Python journey — lesson 61 of 78.
Recursive functions typically have two parts:
- Base Case: Defines when the recursion should stop.
- Recursive Step: Calls the function itself with smaller input.
Example: Calculating factorial using recursion:
def factorial(n):
if n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive call
print(factorial(5)) # Output: 120Here, the function keeps calling itself with n - 1 until it reaches 1, where the recursion stops.
Example: Reversing a String:
def recursive_reverse(s):
if len(s) <= 1: # Base case: empty or single-character string
return s
else:
return recursive_reverse(s[1:]) + s[0] # Recursive step
text = "hello"
result = recursive_reverse(text)
print(result)
# Output: ollehIn this example, the recursive_reverse function calls itself with the rest of the string (s[1:]) until the string is empty or has only one character. Each call appends the first character to the result of the recursive call, effectively reversing the string.
Challenge
EasyWrite a recursive function named fibonacci that takes a positive integer n as an argument and returns the nth Fibonacci number. The Fibonacci sequence is defined as:
fibonacci(1) = 0fibonacci(2) = 1fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)forn > 2.
Example Input:
n = 6Example Output:
5Cheat sheet
Recursive functions have two essential parts:
- Base Case: Defines when the recursion should stop
- Recursive Step: Calls the function itself with smaller input
Factorial example:
def factorial(n):
if n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive call
print(factorial(5)) # Output: 120String reversal example:
def recursive_reverse(s):
if len(s) <= 1: # Base case: empty or single-character string
return s
else:
return recursive_reverse(s[1:]) + s[0] # Recursive step
text = "hello"
result = recursive_reverse(text)
print(result) # Output: ollehTry it yourself
def fibonacci(n):
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter