Function in Python
Function in Python
specific task.Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions
make it more organized and manageable.Furthermore, it avoids repetition and
makes code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
6. One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
The return statement is used to exit a function and go back to the place from
where it was called.
Syntax of return
return [expression_list]
Example
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
# Function Calling
evenOdd(2)
evenOdd(3)
Output:
even
odd
2. Write a python program to find the factorial of any number using function.
f=1
for i in range(1,num+1):
FUNCTION BODY
f=f*i
return f
FUNCTION CALLING
print(fact(num))
The function allows us to implement code reusability. There are three kinds of functions
−
Built-in functions ( As the name suggests, these functions come with the Python language,
for example, help() to ask for any help, max()- to get maximum value, type()- to return the
type of an object and many more.)
User-defined functions ( These are the functions that users create to help them, like the
“sum” function we have created above).
Anonymous Functions (also called lambda functions and unlike normal function which is
defined using def keyword are defined using lambda keyword).
Default arguments:
Output:
('x: ', 10)
('y: ', 50)
Keyword arguments:
The idea is to allow caller to specify argument name with values so that caller does not need to
remember order of parameters.
Output:
('Python', 'Practice')
('Python', 'Practice')
Global variables
Local variables
RECURSIVE FUNCTION
What is recursion?
A physical world example would be to place two parallel mirrors facing each
other. Any object in between them would be reflected recursively.
The following image shows the working of a recursive function called recurses .
Following is an example of a recursive function to find the factorial of an
integer.
Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720 .
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Let's look at an image that shows a step-by-step process of what is going on:
WORKING OF A RECURSIVE FACTORIAL FUNCTION
Our recursion ends when the number reduces to 1. This is called the base
condition.Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.
Advantages of Recursion
Disadvantages of Recursion