Advertisements
Advertisements
प्रश्न
Explain the different types of functions with an example.
Advertisements
उत्तर
|
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
APPEARS IN
संबंधित प्रश्न
Which function is called anonymous un-named function?
While defining a function which of the following symbol is used.
Pick the correct one to execute the given statement successfully.
if ______ : print(x, " is a leap year")
What is a function?
How to set the limit for recursive function? Give an example.
Differentiate ceil() and floor() function?
Write a Python code to check whether a given year is a leap year or not.
What are the points to be noted while defining a function?
Explain the following built-in function.
chr()
Explain the following built-in function.
type()
