English
Tamil Nadu Board of Secondary EducationHSC Science Class 12

Explain the different types of functions with an example.

Advertisements
Advertisements

Question

Explain the different types of functions with an example.

Answer in Brief
Advertisements

Solution

Functions

Description

User-defined functions Functions defined by the users themselves.
Built-in functions Functions that are inbuilt within Python.
Lambda functions Functions that are anonymous un-named functions.
Recursive functions Functions that call themselves are known as recursive.

1. User-defined function:

Functions defined by the users themselves are called User-defined functions.

Syntax:
def :
< Block of statement >
return < expression / None>
Example:
def welcome():
print(“Welcome to Python”)
return

2. Built-in functions:

Functions which are using Python libraries are called Built-in functions.

Example:
x=20
y=-23
print(‘First number = ” ,x)
print(‘Second number = ” ,y)
Output:
First number = 20
Second number = 23

3. Lambda function:

  • The Lambda function is mostly used for creating small and one-time anonymous functions.
  • Lambda functions are mainly used in combination with the functions like filter]), map]) and reduce]).
    Syntax of Lambda function (Anonymous Functions):
    lambda [argument(s)]: expression

Example:
sum = lambda arg1, arg2: arg1 + arg2
print (The Sum is :’, sum(30, 40)
print (The Sum is sum(-30, 40)

Output:
The Sum is: 70
The Sum is: 10

4. Recursive function:

  • A recursive function calls itself. Imagine a process would iterate indefinitely if not stopped by some condition! Such a process is known as infinite iteration.
  • The condition that is applied in any recursive function is known as a base condition.
  • A base condition is a must in every recursive function otherwise it will continue to execute like an infinite loop.
  • Overview of how recursive function works:
  • A recursive function is called by some external code.
  • If the base condition is met then the. the program gives meaningful output and exits.
  • Otherwise, the function does some required processing and then calls itself to continue recursion.
    Here is an example of a recursive function used to calculate factorial.

Example:
def fact(n):
if n==0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))

Output:
1
120

shaalaa.com
Introduction to Python Functions
  Is there an error in this question or solution?
Chapter 7: Python functions - Evaluation [Page 113]

APPEARS IN

Samacheer Kalvi Computer Science [English] Class 12 TN Board
Chapter 7 Python functions
Evaluation | Q 1. | Page 113
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×