functions and recursions in python

Save (0)
Close

Recommended

Description

Functions:

Functions are blocks of code that contain a reusable set of statements. They are defined using the def keyword, followed by the function name, parentheses, and a colon. The code that is included within the function is indented.

In Python, a function may consist of arguments or parameters that can be passed from the calling code to the function. Functions can also return a value or have no return at all. Here’s an example of a function that returns the sum of two numbers:

def sum(a, b):
return a + b

Recursions:

Recursion is a technique in programming that involves calling a function within itself. A function that performs recursion is called a recursive function. The process continues until a specific condition is met or the maximum recursion depth is reached. Recursion is commonly used in solving problems that can be broken down into smaller, similar sub-problems.

Here’s an example of a recursive function that calculates the factorial of a number:

python
def factorial(num):
if num == 1:
return num
else:
return num * factorial(num-1)

In this function, the base case is when the number is equal to 1. The function then calls itself with a smaller value of the input argument until it reaches the base case. The final result is returned when the base case is reached.