CS22-OOP2-Module-7
CS22-OOP2-Module-7
I. INTRODUCTION
In this lesson.
II. OBJECTIVES
1. Define what a function is in Python. Explain
Module 7 the importance of using functions for code
organization and reusability. Understand the
syntax for defining and calling functions.
FUNCTIONS 2. Explore the concept of function parameters
and how they are used. Learn how to return
values from functions, understand the
difference between parameters and
arguments.
3. Explore common built-in functions in Python.
Understand how to use functions.
Page 1 of 4
CS22-OOP2(Object Oriented Programming 2)
College of Computer Studies
Why Functions?
Avoid writing the same code multiple times, re-usability
Be able to name a functionality
Clearly state the functionality of a piece of code, abstraction:
Input = arguments, output = return value (and/or side effects)
Encapsulate code with clear interface to the dependency to the
outside world/code
Share functionality in modules/libraries/packages with other users,
code sharing
Increase readability of code, smaller independent blocks of code
Easier systematically testing of code
Local variables in functions
The formal arguments and variables assigned to in the body of a function
are created as temporary local variables.
Global variables
Variables in function bodies that are only read, are considered access to
global variables.
global
Global variables that should be updated in the function body must be
declared global in the body:
global variable, variable, ...
Note: If you only need to read a global variable, it is not required to be
declared global (but would be polite to the readers of your code).
Page 2 of 4
CS22-OOP2(Object Oriented Programming 2)
College of Computer Studies
In a function call variable will be assigned a tuple with all the additional
arguments.
Unpacking a list of arguments in a function call
If you have list L (or tuple) containing the arguments to a function call, you can
unpack them in the function call using *L
L = [x, y, z]
f(*L)
is equivalent to calling
f(L[0], L[1], L[2])
i.e.
f(x, y, z)
Keyword arguments
Previously we have seen the following (strange) function calls
print(7, 14, 15, sep=":", end="")
enumerate(my_list, start = 1)
Page 3 of 4
CS22-OOP2(Object Oriented Programming 2)
College of Computer Studies
Example- Nested
Function definition
V. PRACTICE EXERCISES/ACTIVITIES
VI. ADDITIONAL RESOURCES
VII. ASSESSMENT
VIII. REFERENCES
Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated
for Python 3, Shroff/O‘Reilly Publishers, 2016
https://www.stat.berkeley.edu/~spector/python.pdf
Page 4 of 4