TOPIC: Python functions - Recursive functions and main function
Recursive functions
In Python, recursive functions are functions that call themselves to solve a problem or perform a
task. Typically, recursive functions have a base case (a condition that stops the recursion) and a
recursive case (a condition that continues the recursion). Here's a structure of a recursive
function
in Python:
def recursive_function(parameters): if base_case: # The base case - the condition where the recursion stops else: # Recursive case - the function calls itself with modified parameters return recursive_function(modified_parameter)Advantages of using recursive functions: 1. Elegance and Readability: Recursive functions often provide elegant and readable solutions to problems, mirroring mathematical descriptions.
main function
In Python, the if __name__ == "__main__": construct is a common idiom used to control the execution
of code in a script. Understanding this construct is essential for writing modular and reusable
code.
def some_function(): # Code for a function def another_function(): # Code for another function if __name__ == "__main__": # Code that should be executed when the script is run print("This code is in the main part of the script.") some_function()
Code as discussed in the video:
# Python Recursive functions and main function
'''
-> Recursive function: a function that calls itself
-> 2 parts: base case, Recursive case
'''
# factorial : 5! = 5 * 4 * 3 * 2 * 1 = 120
# 0! = 1! = 1
# recursive function to find the factorial
# def factorial(n):
# # base case
# if n == 0 or n == 1:
# return 1
# # recursive case
# else:
# return n * factorial(n - 1)
# output = factorial(10)
# print("The factorial of 10 is: ", output)
# main functions
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
def mainFunc():
num = int(input("Enter a number: "))
output = factorial(num)
print(f"The factorial of {num} is:", output)
# main part
if __name__ == "__main__":
mainFunc()
You can copy and run this code