Recursive Functions Part 1
Part of the Logic & Flow section of Coddy's Python journey — lesson 60 of 78.
A recursive function is a function that calls itself to solve smaller instances of a problem. Each recursive call must bring the function closer to a base case, which stops the recursion.
Example: Summing numbers from 1 to n:
def sum_to_n(n):
if n == 0: # Base case
return 0
return n + sum_to_n(n - 1) # Recursive step
print(sum_to_n(5)) # Output: 15Challenge
EasyWrite a recursive function named count_down that takes a positive integer n as an argument and prints each number from n down to 0.
Cheat sheet
A recursive function calls itself to solve smaller instances of a problem. Each recursive call must bring the function closer to a base case, which stops the recursion.
Basic structure:
def recursive_function(parameter):
if base_case_condition: # Base case
return base_value
return recursive_step # Recursive stepExample - summing numbers from 1 to n:
def sum_to_n(n):
if n == 0: # Base case
return 0
return n + sum_to_n(n - 1) # Recursive step
print(sum_to_n(5)) # Output: 15Try it yourself
def count_down(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