Topic 7-Python Functions Modules
Topic 7-Python Functions Modules
Modules
Functions
●
A functions is a reusable named set of
instructions. Below a function is defined and
then used (invoked, called) two different ways:
with literal as arguments and with variables as
arguments.
2
Functions
>>> showInfo("Audrey")
Hello Audrey
Today is Monday
The month is December
The year is 2020
3
Default Arguments
●
You can specify default arguments in the
definition of a function. Then when calling the
function, you have the choice to use the
defaults or replace them with new arguments.
4
Keyword Arguments
●
When calling a function, you can use the
parameter names to specify keyword-value
pairs. The advantage is that arguments do not
have to follow parameter positioning.
>>> minus(5, 4)
def minus(a, b):
1
return a - b
>>> minus(b=5, a=4)
-1
>>>
5
Variable Arguments
●
It is possible to define a Python function that
can accept any number of arguments.
6
Modules
7
Modules
If you need these functions in several
applications, it is tedious to rewrite them
every time.
It is also tedious to look for them and copy
and paste them into a new program every
time.
But even worse, if you need tomodifyo
them, you have to hunt down every file in
which they appear. And there is no
guarantee that you’ll change them
consistently.
8
Modules
9
Importing and Using a Module
1
0
Importing and Using a Module
●
To reduce typing, you can abbreviate a long
module name using the as keyword like this:
1
1
Importing and using a Module
1
2
Testing your Module
1
3
Testing your Module
“ main ”.
1
4
Conditional Execution of Test
Code
1
5
Tutorials
1
6