2/7/2022
Python – Functions
M M MAHBUBUL SYEED, PHD. ASSOCIATE PROFESSOR
Highlights!
• Function – Definition, example.
• Why using Functions??!!
• Function arguments / parameters.
• Function return value.
• Scope of variables - Local and global variables.
1
2/7/2022
Function
DEFINITION
Function
A function is a block of organized, reusable code that is used to perform a single, related action /
task.
Functions provide better modularity for your application and a high degree of code reusing.
Built-in functions in Python: print(), input(), type(), bin(), and many many more ….
User-defined functions: you can define a function as per the need.
2
2/7/2022
Function - Syntax
Function blocks begin with the keyword def Function Passing inputs / parameters (Any
name input parameters) to the function
The code block within
def functionname ( parameters ):
every function starts with a
colon (:)
"function_docstring"
function_suite
[Optional] the documentation
return [expression] string of the function
The code block inside
function must be indented
Returning value from
function when it ends
[Optional]
Function - Example
def functionname ( parameters ):
"function_docstring"
function_suite
return [expression]
def addition(num1, num2):
"This function adds two numbers and returns the value"
num1 = int(num1)
num2 = int(num2)
result = num1 + num2
return result
3
2/7/2022
Function – Calling a function
def addition(num1, num2):
"This function adds two numbers and returns the value"
Function named “addition”
result = int(num1) + int(num2)
return result
n1 = input('Enter number1:')
n2 = input('Enter number2:')
Outside of the function body
res = addition(n1,n2)
print('Result is: ', res)
Function – Calling a function
def addition(num1, num2):
"This function adds two numbers and returns the value"
Function named “addition” 4
result = int(num1) + int(num2)
return result
5
1
Program execution starts here n1 = input('Enter number1:')
2 n2 = input('Enter number2:')
3 4
Call ‘addition’ function with res = addition(n1,n2)
parameters 6 print('Result is: ', res)
4
2/7/2022
Function – Calling a function
1 def printInfo(num1, num2):
2 print(f'We are adding {num1} and {num2}..’)
3 return
4 def addition(num1, num2):
5 "This function adds two numbers and returns the value"
6 result = int(num1) + int(num2)
Can u explain
7 return result
8 the code??
9 n1 = input('Enter number1:')
10 n2 = input('Enter number2:')
11 printInfo(n1,n2)
12 res = addition(n1,n2)
13 print('Result is: ', res)
Why using
Functions??
10
5
2/7/2022
Functions provide a couple of benefits:
Reusability - Functions allow the same piece of code to run multiple times
Modularity - Functions break long programs up into smaller components
Portability - Functions can be shared and used by other programmers
11
Why using Functions??
REF: https://www.futurelearn.com/info/courses/programming-102-think-like-a-computer-scientist/0/steps/53095
12
6
2/7/2022
Each unit is a function
Why using Functions?? - Does a specific task.
- Repetitive.
- Takes specific input.
- Process.
- Produce specific output
REF: https://www.futurelearn.com/info/courses/programming-102-think-like-a-computer-scientist/0/steps/53095
13
Each unit is a function
Why using Functions?? Modular - Does a specific task.
- Repetitive.
Reusable
- Takes specific input.
Portable - Process.
- Produce specific output
REF: https://www.futurelearn.com/info/courses/programming-102-think-like-a-computer-scientist/0/steps/53095
14
7
2/7/2022
Why using Functions??
Lets take a very simple programming example now..
You are supposed to add 5 numbers.. Taking two numbers at a time and adding them..
How this problem can be coded!!?
15
Why using Functions??
You are supposed to add 5 numbers.. Taking two numbers at a time and adding them..
n1 = input('number: ')
n2 = input('number: ')
add = int(n1) + int(n2)
n3 = input('number: ')
add += int(n3)
n4 = input('number: ') Is this a smart solution???
add += int(n4)
n5 = input('number: ')
add += int(n5)
print('Result is: ', add)
16
8
2/7/2022
Why using Functions??
You are supposed to add 5 numbers.. Taking two numbers at a time and adding them..
n1 = input('number: ') def getInput():
n2 = input('number: ') n = input('Enter number: ')
return int(n)
add = int(n1) + int(n2)
n3 = input('number: ') def addnumber(n1, n2):
add += int(n3) return n1+n2
n4 = input('number: ') add = addnumber(getInput(), getInput())
add += int(n4)
add = addnumber(add, getInput())
n5 = input('number: ') add = addnumber(add, getInput())
add += int(n5) add = addnumber(add, getInput())
print('Result is: ', add)
print('Result is: ', add)
17
Passing inputs / parameters (Any
input parameters) to the function
Function
Arguments /
def functionname ( parameters ):
"function_docstring"
Parameters function_suite
return [expression]
18
9
2/7/2022
Function Arguments / Parameters
You can call a function by using the following types of formal arguments-
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
19
Required arguments
Required arguments are the arguments passed to a function in correct positional order.
The number of arguments in the function call should match exactly with the function definition.
def printme( str, name ):
"This prints a passed string into this function"
line 7, in <module>
print (str , name)
printme()
return TypeError: printme() missing 2 required positional
arguments: 'str' and 'name'
# Now you can call printme function line 8, in <module>
printme() printme()
TypeError: printme() missing 1 required positional
printme("This is me with name") arguments: 'name'
printme('This is me, ', 'My name is Rajit.')
What about this call??
20
10
2/7/2022
Keyword arguments
Keyword arguments are related to the function calls.
When use keyword arguments in a function call, the caller identifies the arguments by the parameter
name.
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" ) Keyword argument!
printinfo(age=50, "miki" )
Produce Error!!!
printinfo(age = 30)
21
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
def printinfo( name = 'Rajit', age = 35):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
Name: miki
Age 50
# Now you can call printinfo function Name: Samah
Age 35
printinfo( age=50, name="miki" )
Name: Rajit
printinfo( name = 'Samah') Age 35
printinfo()
22
11
2/7/2022
Variable-length arguments
Some time we need to pass variable number of arguments to the function.
These arguments are called variable-length arguments.
An asterisk (*) is placed before the variable name. It holds the values as tuple.
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ('Required argument: ', arg1) Required argument: 70
variable arguments:
print ('variable arguments: ') 60
for var in vartuple: Rajit
print (var) Required argument: 10
return variable arguments:
# Now you can call printinfo function
printinfo( 70, 60, 'Rajit' )
printinfo( 10 )
23
def functionname ( parameters ):
"function_docstring"
Function function_suite
return return [expression]
Statement Returning value from
function when it ends
[Optional]
24
12
2/7/2022
Function return Statement
The statement return [expression] exits a function.
Optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
def printinfo( name = 'Rajit', age = 35):
def func():
"This prints a passed info into this function"
n1 = 20
print ("Name: ", name)
n2 = 'Rajit'
print ("Age ", age)
return [n1,n2]
return
n3 = func()
print(n3[0], n3[1]) # Now you can call printinfo function
printinfo( age=50, name="miki" )
Function func() returns a tuple of values Function printinfo() returns nothing
25
Scope of
Variables
26
13
2/7/2022
Scope of variable – Global or Local
Local variable: Variables that are defined inside a function body have a local scope.
Global Variable: Variables defined outside any function have a global scope.
Local variables are accessible only inside the function in which they are declared.
Global variables can be accessed throughout the program body by all functions.
27
Scope of variable – Global or Local
Local variable: Variables that are defined inside a function body have a local scope.
Global Variable: Variables defined outside any function have a global scope.
def afunction():
n3 = 35 Local Variable
return
def functest():
n1 = 'This is local variable' Local Variable
return
n3 = 'This is global variable' Global Variable
28
14
2/7/2022
Scope of variable – Global or Local
def afunction(): Can you trace the output?
n3 = 35
print('local n3 = ', n3)
print('Global (inside function) n2= ', n2)
return
local n3 = 35
Global (inside function) n2= This is global variable
n2 = 'This is global variable' Global (outside function) n2= This is global variable
Traceback (most recent call last): functionargument.py",
afunction()
line 51, in <module>
print('Local of afunction() n3: ', n3)
print('Global (outside function) n2= ', n2)
NameError: name 'n3' is not defined. Did you mean: 'n2'?
print('Local of afunction() n3: ', n3)
29
Problem Set!
30
15
2/7/2022
1. Write a Python function to find the Max of two numbers.
2. Write a Python function to check whether a number falls in a given range. The function will
take 3 numbers as input, first one the number to be checked, 2nd and 3rd number for range.
3. Write a Python function that takes a number as a parameter and check whether it is even or
odd.
31
Suppose you have started working on an hourly basis as a librarian in your institution. You want to know how
much you will earn a month given that you know how many hours you will work per week and how much you
receive per hour. However, whatever amount you earn per month will have 20% of it deducted and that
amount will be instead used to pay part of your tuition fees. Write a program that finds out the earnings before
and after the deduction. Also find out the yearly earnings (without deduction) and how much of your tuition
fees you are paying yourself annually. Assume that there are 4 weeks per month.
Enter the number of hours you will work per week: 20
Enter the amount you earn per hour: BDT. 150
Monthly earning: BDT. 12000
Monthly earning after deduction: BDT. 9600
Yearly earning: BDT. 144000
Amount paid as tuition fees per year: BDT. 28800
Write a function named calculateEarning() that will calculate the monthly earning, earning after deduction,
yearly earning and amount to be paid as tuition fees.
calculateEarning() function should take weekly hour and earning per hour as parameters.
32
16