7 Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

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

def Display(Name, age):


print(“Name = “, Name, ”age = “, age)

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.

def Display(Name, age):


print(“Name = “, Name, ”age = “, age)

Display(age=25,Name=”John”) #Call function using keyword arguments


Parameter with Default Values
• We can provide default value to a parameter by
using the assignment (=) operator.

def greet(name, msg=”Welcome to Python!!”):


print(“ Hello “,name, msg)

greet(“Sachin”)

def greet(name, msg = "Good morning!"):


print("Hello",name + ', ' + msg)

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):

We would get an error as:


SyntaxError: non-default argument follows default argument
Arbitrary Number of Parameters
(Variable length arguments)
• There are many situations in programming, in
which the exact number of necessary parameters
cannot be determined a-priori.
• An arbitrary parameter number can be
accomplished in Python with so-called tuple
references.
• An asterisk "*" is used in front of the last
parameter name to denote it as a tuple reference.
• This asterisk shouldn't be mistaken with the C
syntax, where this notation is connected with
pointers.
def sum(*n):
total=0
for i in n:
total=total + i
print("The Sum=",total)

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

• In the previous chapter we demonstrated how to


pass an arbitrary number of positional parameters
to a function.
• It is also possible to pass an arbitrary number of
keyword parameters to a function.
• To this purpose, we have to use the double asterisk
"**"
>>> def f(**kwargs):
print(kwargs)

>>> 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)

Value inside function: 10


Value outside function: 20
THE LOCAL AND GLOBAL SCOPE OF A VARIABLE
• Variables and parameters that are initialized within a function
- local variables.
• Variables that are assigned outside functions - global variables.
p = 20 #global variable p
def Demo( ):
q = 10 #Local variable q
print(‘The value of Local variable q:’,q) #Access global variable p within this
function
print(‘The value of Global Variable p:’,p)

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

• It is possible to return multiple values in Python


def calc_arith_op(num1, num2):
return num1+num2, num1-num2
#Return multiple values

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

print(cube(2)) #Call lambda function

Output: 8

greet = lambda : print('Hello World') # define lambda function

greet() # call lambda function

Output: Hello World

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy