Python Function Elements

To pass a group of elements like numbers or strings, we can accept them into a list and then pass the list to the function where the required processing can be done. In below Program, we are accepting a group of integers from the keyboard in a single line using the following statement:

lst = [int(x) for x in input().split()]

The input() function takes a group of integers as a string. This string is split into pieces where a space is found as a space is the default for split() method. These pieces are then converted into integers by the int() function and returned into the list 'lst'. We pass this list of integers to the calculate() function as:

x, y = calculate(lst)

Group function elements

The following example is a function to display a group of strings.

CopiedCopy Code

def display(lst): 
 for i in lst: 
     print(i) 
lst = [x for x in input('Enter strings separated by comma:').split(',')] 
display(lst)

The following example is a function to accept a group of numbers and find their total average.

CopiedCopy Code

def calculate(lst):
   n = len(lst) 
   sum=0 
   for i in lst: 
      sum+=i
   avg = sum/n 
   return sum, avg 
lst = [int(x) for x in input('Enter numbers separated by space:').split()] 
x, y = calculate(lst) 
print('Total:', x) 
print('Average:', y)

Recursive function

A function that calls itself is known as 'recursive function'. For example, we can write the factorial of 3 as:

factorial(3) = 3 * factorial(2)

Here, factorial(2) = 2 * factorial(1)

And, factorial(1) = 1 * factorial(0)

factorial(3) = 3 * factorial(2)

= 3 * 2 * factorial(1)

= 3 * 2 * 1 * factorial(0)

= 3 * 2 * 1 * 1 = 6

From the above statements, we can write the formula to calculate factorial of any number 'n' as:

factorial(n) = n * factorial(n-1)

Recursive Function Examples:

A Python program to calculate factorial using recursion.

CopiedCopy Code

def factorial(n): 
   if n==0 or n==1: 
      return 1 
   else: 
      return n*factorial(n-1) 
n=int(input("Enter a Number: "))
res=factorial(n)
print("Factorial of %d is %d " %(n,res))

A Python program to calculate factorial values using recursion.

CopiedCopy Code

def factorial(n): 
   if n==0: 
      result=1 
   else: 
      result=n*factorial(n-1) 
   return result 
for i in range(1, 11): 
print('Factorial of {} is {}'.format(i, factorial(i)))