FUNCTIONS
VALUE TO MULTIPLE VARIABLES
x, y, z = "Orange", "Banana", "Cherry"
a, b, c = 0.1, 100, 'string'
print(x)
print(y) print(a)
print(z) print(b)
print(c)
x = y = z = "Orange" print("assigning values of different datatypes")
print(x) a, b, c, d = 4, “hello", 3.14, True
print(y) print(a)
print(z) print(b)
print(c)
print(d)
FUNCTION
PYTHON FUNCTION IS A SEQUENCE OF STATEMENTS THAT EXECUTE IN A CERTAIN ORDER, WE
ASSOCIATE A NAME WITH IT
FUNCTIONS CAN BE USED TO DEFINE REUSABLE CODE AND ORGANIZE AND SIMPLIFY CODE
DEFINING A FUNCTION
def functionName(list of parameters)
# Function body
FUNCTION
CALLING A FUNCTION
Calling a function executes the code in the function
The program that calls the function is called a caller
max() Without argument
max(3, 4) With argument
larger = max(3, 4)
With argument and return value
print(max(3, 4))
CALLING A FUNCTION
def my_function():
def my_function(fname):
print("Hello from a function") print(fname + " Refsnes")
my_function() my_function("Emil")
my_function("Tobias")
my_function("Linus")
FIND THE ERROR
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
PARAMETERS OR ARGUMENTS
The terms parameter and argument can be used for the same thing: information that are passed into a function
a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
5 TYPES OF ARGUMENTS IN PYTHON FUNCTION DEFINITION:
default arguments
keyword arguments
positional arguments
arbitrary positional arguments
arbitrary keyword arguments
1. DEFAULT ARGUMENTS
Default arguments are values that are provided while defining functions.
The assignment operator = is used to assign a default value to the argument.
Default arguments become optional during the function calls.
If we provide a value to the default arguments during function calls, it overrides the default value.
The function can have any number of default arguments
Default arguments should follow non-default arguments
EXAMPLE
def greet(name, msg="Good morning!"): def greeting(name='User'):
print("Hello", name + ', ' + msg) print(f"Hello, {name}")
greeting('Ayushi')
greet("Kate")
greet("Bruce", "How do you do?")
1. Giving only the mandatory argument
EXAMPLE
print(add(3))
#Output:18
2. Giving one of the optional arguments.
def add(a,b=5,c=10): 3 is assigned to a, 4 is assigned to b.
return (a+b+c)
This function can be called in 3 ways print(add(3,4))
#Output:17
3. Giving all the arguments
print(add(2,3,4))
#Output:9
DEFAULT PARAMETER VALUE
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
2. KEYWORD ARGUMENTS
Functions can also be called using keyword arguments of the form kwarg=value
A function’s arguments can be passed as positional keyword arguments
When we call a function with some values, these values get assigned to the arguments according to their position
Python allows functions to be called using keyword arguments.
call functions in this way, the order (position) of the arguments can be changed
EXAMPLE
1. All parameters are given as keyword arguments, so no
need to maintain the same order.
def add(a,b=5,c=10): print (add(b=10,c=15,a=20))
return (a+b+c) #Output:45
Calling the function add by giving keyword
2. During a function call, only giving mandatory argument
arguments
as a keyword argument. Optional default arguments are
skipped.
print (add(a=10))
#Output:25
EXAMPLE
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
3. POSITIONAL ARGUMENTS
During a function call, values passed through arguments should be in the order of parameters in the function definition.
This is called positional arguments
Keyword arguments should follow positional arguments only
EXAMPLE
1. During the function call, all arguments are given as positional
arguments.
• Values passed through arguments are passed to parameters by
their position. 10 is assigned to a, 20 is assigned to b and 30 is
assigned to c.
def add(a,b,c):
return (a+b+c) print (add(10,20,30))
The above function can be called in two #Output:60
ways:
2. Giving a mix of positional and keyword arguments, keyword
arguments should always follow positional arguments
print (add(10,c=30,b=20))
#Output:60
DEFAULT VS POSITIONAL VS KEYWORD ARGUMENTS
IMPORTANT POINTS
1. DEFAULT ARGUMENTS SHOULD FOLLOW NON-DEFAULT
ARGUMENTS
def add(a=5,b,c):
return (a+b+c)
#Output:SyntaxError: non-default argument follows default argument
2. KEYWORD ARGUMENTS SHOULD FOLLOW POSITIONAL
ARGUMENTS
def add(a,b,c):
return (a+b+c)
print (add(a=10,3,4))
#Output:SyntaxError: positional argument follows keyword argument
3. ALL THE KEYWORD ARGUMENTS PASSED MUST MATCH ONE OF
THE ARGUMENTS ACCEPTED BY THE FUNCTION AND THEIR
ORDER IS NOT IMPORTANT.
def add(a,b,c):
return (a+b+c)
print (add(a=10,b1=5,c=12))
#Output:TypeError: add() got an unexpected keyword argument 'b1'
4. NO ARGUMENT SHOULD RECEIVE A VALUE MORE THAN ONCE
def add(a,b,c):
return (a+b+c)
print (add(a=10,b=5,b=10,c=12))
#Output:SyntaxError: keyword argument repeated
5. DEFAULT ARGUMENTS ARE OPTIONAL ARGUMENTS
Example 1: Giving only the mandatory arguments
def add(a,b=5,c=10):
return (a+b+c)
print (add(2))
#Output:17
Example 2: Giving all arguments (optional and mandatory arguments)
def add(a,b=5,c=10):
return (a+b+c)
print (add(2,3,4))
#Output:9
VARIABLE-LENGTH ARGUMENTS
Two types of arbitrary arguments
arbitrary positional arguments
arbitrary keyword arguments
4. ARBITRARY POSITIONAL ARGUMENTS
It may not always be known how many arguments will be there. In that case, put an asterisk(*) before an
argument name
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in
the function definition
This way the function will receive a tuple of arguments, and can access the items accordingly:
EXAMPLES
def add(*b):
result=0 def my_function(*kids):
for i in b: print("The youngest child is " + kids[2])
result=result+i
return result
my_function("Emil", "Tobias", "Linus")
print (add(1,2,3,4,5))
#Output:15
print (add(10,20))
#Output:30
EXAMPLES def add(*b): def greet(*names):
result=0 """This function greets all
the person in the names tuple."""
for i in b:
result=result+i # names is a tuple with arguments
return result for name in names:
print("Hello", name)
print (add(1,2,3,4,5))
#Output:15
greet("Monica", "Luke", "Steve", "John")
print (add(10,20))
#Output:30
def sayhello(*names):
for name in names:
print(f"Hello, {name}")
sayhello('Ayushi','Leo','Megha')
5.ARBITRARY KEYWORD ARGUMENTS
For arbitrary positional argument, a double asterisk (**) is placed before a parameter in a function which can hold
keyword variable-length arguments.
EXAMPLE
def fn(**a):
for i in a.items():
print (i)
fn(numbers=5,colors="blue",fruits="apple")
'''
Output:
('numbers', 5)
('colors', 'blue')
('fruits', 'apple')
'''
SPECIAL PARAMETERS
By default, arguments may be passed to a Python function either by position or explicitly by keyword. For readability
and performance, it makes sense to restrict the way arguments can be passed so that a developer need only look at the
function definition to determine if items are passed by position, by position or keyword, or by keyword.
A function definition may look like:
SPECIAL PARAMETERS
Where / and * are optional. If used, these symbols indicate the kind of parameter by how the arguments may be passed to the
function: positional-only, positional-or-keyword, and keyword-only.
Positional or keyword arguments
Positional only parameters
Keyword-only arguments
1. POSITIONAL OR KEYWORD ARGUMENTS
If / and * are not present in the function definition, arguments may be passed to a function by position or by keyword
def add(a,b,c):
return a+b+c
print (add(3,4,5))
#Output:12
print (add(3,c=1,b=2))
#Output:6
2. POSITIONAL ONLY PARAMETERS
Positional-only parameters are placed before a / (forward-slash) in the function definition. The / is used to logically
separate the positional-only parameters from the rest of the parameters. Parameters following the / may be positional-or-
keyword or keyword-only.
def add(a,b,/,c,d):
return a+b+c+d
print (add(3,4,5,6))
#Output:12
print (add(3,4,c=1,d=2))
#Output:6
2. POSITIONAL ONLY PARAMETERS
If we specify keyword arguments for positional only arguments, it will raise TypeError.
def add(a,b,/,c,d):
return a+b+c+d
print (add(3,b=4,c=1,d=2))
#Output:TypeError: add() got some positional-only
arguments passed as keyword arguments: 'b'
3. KEYWORD ONLY ARGUMENTS
To mark parameters as keyword-only, place an * in the arguments list just before the first keyword-only parameter.
def add(a,b,*,c,d):
return a+b+c+d
print (add(3,4,c=1,d=2))
#Output:10
3. KEYWORD ONLY ARGUMENTS
If we specify positional arguments for keyword-only arguments it will raise TypeError.
def add(a,b,*,c,d):
return a+b+c+d
print (add(3,4,1,d=2))
#Output:TypeError: add() takes 2 positional arguments but 3
positional arguments (and 1 keyword-only argument) were
given
ALL 3 CALLING CONVENTIONS ARE USED IN THE SAME FUNCTION
In the below-given example, the function add has all three arguments
a,b — positional only arguments
c-positional or keyword arguments
d-keyword-only arguments
def add(a,b,/,c,*,d):
return a+b+c+d
print (add(3,4,1,d=2))
#Output:10
IMPORTANT POINTS TO REMEMBER
Use positional-only if you want the name of the parameters to not be available to the user. This is useful when parameter
names have no real meaning.
Use positional-only if you want to enforce the order of the arguments when the function is called.
Use keyword-only when names have meaning and the function definition is more understandable by being explicit with
names.
Use keyword-only when you want to prevent users from relying on the position of the argument being passed.
RETURN VALUES
To let a function return a value, use the return statement
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
def add(a, b):
# A Python program to return multiple
# values from a method using tuple
# returning sum of a and b
return a + b
# This function returns a tuple
def fun():
def is_true(a): str = “ZONEofEMERGINGeLECTRONICS"
x = 20
return str, x; # Return tuple, we could
# returning boolean of a
return bool(a)
also
# write (str, x)
# calling function # Driver code to test above method
res = add(2, 3) str, x = fun() # Assign returned tuple
print("Result of add function is {}".format(res))
print(str)
print(x)
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))
RETURNING MULTIPLE VALUES
Using Object
Using Tuple
Using List
Using a Dictionary
Using Data Class (Python 3.7+)
def statFun(a, b):
difference = a-b
percent_diff = (difference/a)*100
return difference, percent_diff;
difference, percent_diff = statFun()
print (difference) print (percent_diff)
USING OBJECT
# A Python program to return multiple
# values from a method using class
class Test:
def __init__(self):
self.str = "geeksforgeeks"
self.x = 20
# This function returns an object of Test
def fun():
return Test()
# Driver code to test above method
t = fun()
print(t.str)
print(t.x)
USING TUPLE
# A Python program to return multiple
# values from a method using tuple
# This function returns a tuple
def fun():
str = "geeksforgeeks"
x = 20
return str, x; # Return tuple, we could also
# write (str, x)
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)
USING A LIST
# A Python program to return multiple
# values from a method using list
# This function returns a list
def fun():
str = "geeksforgeeks"
x = 20
return [str, x];
# Driver code to test above method
list = fun()
print(list)
USING A DICTIONARY
# A Python program to return multiple
# values from a method using dictionary
# This function returns a dictionary
def fun():
d = dict();
d['str'] = "GeeksforGeeks"
d['x'] = 20
return d
# Driver code to test above method
d = fun()
USING DATA
CLASS
(PYTHON 3.7+)
NONE FUNCTION
Technically, every function in Python returns a value whether you use return or not.
If a function does not return a value, by default, it returns a special value None.
For this reason, a function that does not return a value is also called a None function.
Check Output
def sum(number1, number2):
total = number1 + number2
print(sum(1, 2))
RECURSION
Python also accepts function recursion, which means a defined function can call itself
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit
of meaning that you can loop through data to reach a result
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power
TRI_RECURSION()
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
QUESTIONS
What are the benefits of using a function?
How do you define a function? How do you invoke a function?
Can you have a return statement in a None function? Does the return statement in the following function cause syntax
errors?
def xFunction(x, y):
print(x + y)
return
QUESTIONS
Identify and correct the errors in the following program
Show the output of the following code:
What error will occur when you run the following code?