functions and recursions in python




functions and recursions in python

Functions in Python:

Functions in Python are a set of statements that can be defined to be executed repeatedly in a program. A Python function is defined using the ‘def’ keyword followed by the function name, parentheses, and a colon. The body of the function is indented and contains the statements to be executed when the function is called. A function can have zero or more parameters or arguments, which are used to pass values to the function.

Function Example:

Here is an example of a function add() that takes two arguments and returns the sum of the two:

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

#calling the function
c = add(2, 3)
print(c) #Output: 5

Recursion in Python:

Recursion is a technique in which a function calls itself repeatedly until a base case is reached. The recursion function is defined with a base case that acts as the stopping condition. The recursion function calls itself with a new parameter that is closer to the base case than the original parameter. Recursion is a powerful technique that allows you to solve problems that can be broken down into smaller problems of the same type.

Recursion Example:

Here is an example of a recursion function that calculates the factorial of a given number:

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

#calling the function
print(factorial(5)) # Output: 120

In the above example, if the value of num is equal to 1, the function returns 1. Otherwise, the function calls itself with num-1 as the parameter until the base case is reached. The final result is the multiplication of num with the result returned by the function called with num-1 as the parameter.

Related Posts