Agenda
1. Functions
2. Creating a function
3. Calling a function
4. Arguments
Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability
Creating a Function
• A function is defined using the def keyword
Example:
def my_function():
print("Hello from a function")
Calling a Function
def my_function():
print("Hello from a function")
my_function()
Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
Example
def my_function(fname):
print(fname +" Welcome ")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Function with 2 arguments
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Example
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Types of Function Arguments
we have the following 4 types of function arguments.
• Default argument
• Keyword arguments (named arguments)
• Positional arguments
• Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Parameter Value
• A default argument is a parameter that assumes a default value if a value
is not provided in the function call for that argument.
• If we call the function without argument, it uses the default value
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Example
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# We call myFun() with only argument
myFun(10)
Keyword Arguments
• The idea is to allow the caller to specify the argument name with values so
that the caller does not need to remember the order of parameters.
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Example
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Python', lastname='Practice')
student(lastname='Practice', firstname='Python')
Positional Arguments
We used the position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or
value) is assigned to age. By changing the position, or if you forget the
order of the positions, the values can be used in the wrong places, as
shown in the Case-2 example below, where 27 is assigned to the name
and Suraj is assigned to the age.
Example
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
Arbitrary Arguments, *args
• Arbitrary Keyword Arguments,*args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two
special symbols:
• *args in Python (Non-Keyword Arguments)
• **kwargs in Python (Keyword Arguments)
Non-Keyword Arguments
• 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.
Example
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Example
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', ‘PythonLearning')
Example
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
• This way the function will receive a dictionary of arguments, and can
access the items accordingly:
Example
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
def keyword_arguments(**a):
print(a["lname"])
print(a["fname"], a["mname"], a["lname"])
keyword_arguments(fname="Iniyavan", lname="Elakiyan", mname="Dave")
Example
# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print(key, value)
# Driver code
myFun(first=“Geeks”, mid=“for”, last=“Test”)
Example
# This program is about Arbitrary Keyword Arguments
def keyword_arguments(**a):
print(a["lname"])
print(a["fname"], a["mname"], a["lname"])
def keyword_arguments_dictionary(*a):
print(a)
for value in a:
print(value)
def keyword_arguments_dictionary_1(**a):
print(a)
for key, value in a.items():
print(key, value)
keyword_arguments(fname="Iniyavan", lname="Elakiyan", mname="Dave")
keyword_arguments_dictionary("Iniyavan", "Elakiyan", "Dave")
keyword_arguments_dictionary_1(first_name="Iniyavan", last_name="Elakiyan",
middle_name="Dave")
Docstring
• The first string after the function is called the Document string or
Docstring in short. This is used to describe the functionality of the
function. The use of docstring in functions is optional but it is considered a
good practice.
• The below syntax can be used to print out the docstring of a function:
• Syntax: print(function_name.__doc__)
Example
# whether x is even or odd
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
print(evenOdd.__doc__)
Passing a List as an Argument
• You can send any data types of argument to a function (string, number,
list, dictionary etc.), and it will be treated as the same data type inside the
function.
• E.g. if you send a List as an argument, it will still be a List when it reaches
the function
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
• To let a function return a value, use the return statement
• The function return statement is used to exit from a function and go back
to the function caller and return the specified value or data item to the
caller.
• The syntax for the return statement is:
return [expression_list]
• The return statement can consist of a variable, an expression, or a
constant which is returned at the end of the function execution. If none of
the above is present with the return statement a None object is returned.
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Example
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Pass by Reference and Pass by Value
• One important thing to note is, in Python every variable name is a
reference. When we pass a variable to a function, a new reference to the
object is created.
Example
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
# Driver Code (Note that lst is modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Continued
When we pass a reference and change the received reference to something
else, the connection between the passed and received parameter is
broken.
Example
def myFun(x):
# After below line link of x with previous
# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]
# Driver Code (Note that lst is not modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Example
def myFun(x):
# After below line link of x with previous
# object gets broken. A new object is assigned
# to x.
x = 20
# Driver Code (Note that x is not modified
# after function call.
x = 10
myFun(x)
print(x)
Example
def swap(x, y):
temp = x
x=y
y = temp
# Driver code
x=2
y=3
swap(x, y)
print(x)
print(y)
The pass Statement
Function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid
getting an error.
Example:
def myfunction():
pass
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. However, when
written correctly recursion can be a very efficient and mathematically-
elegant approach to programming.
• In this example, tri_recursion() is a function that we have defined to call
itself ("recurse"). We use the k variable as the data, which decrements (-
1) every time we recurse. The recursion ends when the condition is not
greater than 0 (i.e. when it is 0).
Example
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)
Function within Functions
• A function that is defined inside another function is known as the inner
function or nested function. Nested functions are able to access variables
of the enclosing scope. Inner functions are used so that they can be
protected from everything happening outside the function.
Example
def f1():
s = 'I love GeeksforGeeks'
def f2():
print(s)
f2()
# Driver's code
f1()
Anonymous Functions
# using lambda function
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))