7 Functions
7 Functions
7 Functions
Function
• A function is a self-contained block of one or more
statements that performs a special task when called.
• The syntax for defining a function is given as follows:
def name_of_function(Parameters):
statement1
statement2
……………………………
……………………………
statementN
def add(x,y): def even_odd(num):
return x+y if num%2==0:
print(num,"is Even Number")
result=add(10,20) else:
print("The sum is",result) print(num,"is Odd Number")
print("The sum is",add(100,200))
even_odd(10)
even_odd(15)
Output Output
The sum is 30 10 is Even Number
The sum is 300 15 is Odd Number
Python Docstrings
• Docstrings, short for documentation strings, are
vital in conveying the purpose and functionality of
Python functions, modules, and classes.
• Declaring Docstrings: The docstrings are declared
using ”’triple single quotes”’ or “”” triple double
quotes “”” just below the class, method, or
function declaration. All functions should have a
docstring.
• Accessing Docstrings: The docstrings can be
accessed using the __doc__ method of the object
or using the help function.
Python Docstrings
def my_function():
'''Demonstrates triple double quotes
docstrings and does nothing really.'''
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
PARAMETERS AND ARGUMENTS IN A FUNCTION
• Positional Arguments
• Keyword Arguments
• Parameter with Default Values
• Variable length arguments
Positional Arguments
• The parameters are assigned by default according to
their position, i.e. the first argument in the call statement
is assigned to the first parameter listed in the function
definition.
• Similarly, the second argument in the call statement is
assigned to the second parameter listed in the function’s
definition and so on
Display(“John”,25)
Display(40,”Sachin”)
Keyword Arguments
• A programmer can pass a keyword argument to a
function by using its corresponding parameter name
rather than its position.
• This can be done by simply typing Parameter_name =
value in the function call.
greet(“Sachin”)
greet("Kate")
greet("Bruce","How do you do?")
Parameter with Default Values
• Any number of arguments in a function can have a
default value. But once we have a default argument, all
the arguments to its right must also have default
values.
• This means to say, non-default arguments cannot
follow default arguments.
• For example, if we had defined the function header
above as:
def greet(msg = "Good morning!", name):
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)
Output
The Sum= 0
The Sum= 10
The Sum= 30
The Sum= 100
def arithmetic_mean(first, *values):
""" This function calculates the arithmetic mean of a
non-empty arbitrary number of numerical values """
return (first + sum(values)) / (1 + len(values))
print(arithmetic_mean(45,32,89,78))
print(arithmetic_mean(8989.8,78787.78,3453,78778.73))
print(arithmetic_mean(45,32))
print(arithmetic_mean(45))
Results:
61.0
42502.3275
38.5
45.0
Arbitrary Number of Keyword Parameters
>>> f()
{}
>>> f(de="German",en="English",fr="French")
{'de': 'German', 'en': 'English‘, 'fr': 'French'}
>>>
Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the variable is
recognized.
• Parameters and variables defined inside a function is not visible from outside.
• Hence, they have a local scope.
• Lifetime of a variable is the period throughout which the variable exits in the
memory.
• The lifetime of variables inside a function is as long as the function executes.
• They are destroyed once we return from the function.
• Hence, a function does not remember the value of a variable from its previous
calls.
• Here is an example to illustrate the scope of a variable inside a function.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Demo( )
#Access global variable p outside the function Demo( )
print(‘The value of global variable p:’,p)
Output
The value of Local variable q: 10
The value of Global Variable p: 20
The value of global variable p: 20
Reading Global Variables from a Local Scope
def Demo( ):
print(S)
Output :
S=’I Love Python’ I Love Python
Demo( )
Local and Global Variables with the Same Name
def Demo():
S=’I Love Programming’
Output
print(S) I Love
Programming
S=’I Love Python’
Demo()
I Love Python
print(S)
The Global Statement
• The global keyword has been used before the name of the
variable to change the value of the local variable
a = 20
def Display( ):
global a
a = 30
print(‘ The value of a in function :’, a)
Display( )
print(‘The value of an outside function :’, a)
Output
The value of a in function: 30
The value of an outside function: 30
THE return STATEMENT
• The return statement is used to return a value from the function.
def getResult (a,b):
t=a+b
return t
r=getResult(4,5)
print(r)
Output: 9
print(“ “,calc_arith_op(10,20))
Output
(30, -10)
RECURSIVE FUNCTIONS
• Python also supports the recursive feature, which
means that a function is repetitively called by itself.
• Thus, a function is said to be recursive if a statement
within the body of the function calls itself.
• Formula to calculate the factorial of a number (n)! = n*(n-1)!
5! = 5*(4)! def factorial(n):
= 5*4*(3)! if n==0:
= 5*4*3*(2)! return 1
= 5*4*3*2*(1) return n*factorial(n-1)
= 120 print(factorial(5))
Output
120
Recursive Functions
def fib(n): def gcd(a,b):
if n == 1: if(b==0):
return 1 return a
elif n == 2: else:
return 1 return gcd(b,a%b)
else:
return fib(n-1) + fib(n-2) a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
for i in range(1,7,1) GCD=gcd(a,b)
print(fib(i),end=“ “) print("GCD is: “,GCD)
THE LAMBDA FUNCTION
• Lambda functions are named after the Greek letter l
(lambda).
• These are also known as anonymous functions.
• Name = lambda(variables/arguments): Code/expression
• A lambda function can take any number of arguments, but
can only have one expression.
x = lambda a : a + 10 str1 = 'GeeksforGeeks'
print(x(5)) upper = lambda string:string.upper()
print(upper(str1))
x = lambda a, b : a * b
print(x(5, 6)) #Lambda function with if-else
Max = lambda a, b : a if(a > b) else b
x = lambda a, b, c : a + b + c print(Max(1, 2))
print(x(5, 6, 2))
cube = lambda x: x*x*x #Define lambda function
Output: 8