3 1 Functions
3 1 Functions
Python – Functions
M M MAHBUBUL SYEED, PHD. ASSOCIATE PROFESSOR
Highlights!
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 ….
2
2/7/2022
Function - Syntax
Function blocks begin with the keyword def Function Passing inputs / parameters (Any
name input parameters) to the function
function_suite
[Optional] the documentation
return [expression] string of the function
Function - Example
def functionname ( parameters ):
"function_docstring"
function_suite
return [expression]
num1 = int(num1)
num2 = int(num2)
return result
3
2/7/2022
n1 = input('Enter number1:')
n2 = input('Enter number2:')
Outside of the function body
res = addition(n1,n2)
print('Result is: ', res)
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
Why using
Functions??
10
5
2/7/2022
Reusability - Functions allow the same piece of code to run multiple times
11
REF: https://www.futurelearn.com/info/courses/programming-102-think-like-a-computer-scientist/0/steps/53095
12
6
2/7/2022
REF: https://www.futurelearn.com/info/courses/programming-102-think-like-a-computer-scientist/0/steps/53095
13
REF: https://www.futurelearn.com/info/courses/programming-102-think-like-a-computer-scientist/0/steps/53095
14
7
2/7/2022
You are supposed to add 5 numbers.. Taking two numbers at a time and adding them..
15
n1 = input('number: ')
n2 = input('number: ')
n3 = input('number: ')
add += int(n3)
n5 = input('number: ')
add += int(n5)
16
8
2/7/2022
17
Function
Arguments /
def functionname ( parameters ):
"function_docstring"
Parameters function_suite
return [expression]
18
9
2/7/2022
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.
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.
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.
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.
23
"function_docstring"
Function function_suite
24
12
2/7/2022
n3 = func()
print(n3[0], n3[1]) # Now you can call printinfo function
printinfo( age=50, name="miki" )
25
Scope of
Variables
26
13
2/7/2022
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
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
28
14
2/7/2022
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
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.
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