Python-Chapter 1
Python-Chapter 1
Python-Chapter 1
CHAPTER 2:
FUNCTIONS, MODULES AND
PACKAGES
2
CHAPTER OUTCOMES
• By the end of this chapter, the students will:
• Know how to write and create functions, modules as well as packages to solve
complex problems
• Know how to define and call a function (passing the correct corresponding
arguments)
• Be able to apply and use Python built-in functions and modules
3
PART 1 – FUNCTIONS
4
FUNCTIONS IN PYTHON
• The functions in Python are:
• Built-in functions: these functions pre-defined and are always
available.
• User defined functions: these are defined by the programmer.
• Functions defined in modules: these functions are pre-defined in
particular modules and can only be used when the corresponding
module is imported.
5
BUILT-IN FUNCTIONS
• The Python interpreter has a number of functions built into it that are
always available:
print():Prints to the standard output device
abs(x): Returns the absolute value of a number
float(): Returns a floating point number
int(): Returns an integer number
str(): Returns a string object
input():Allowing user input
len(): Returns the length of an object
list(): Returns a list
pow(x,y): Returns the value of x to the power of y
tuple(): Returns a tuple
sum(): Sums the items of an iterator
dir(str):Lists all the string function names
dir(list):Lists all the list function names
dir(dict):Lists all the dictionary function names
dir(tuple):Lists all the tuple function names
…
6
join(string): takes all items in an iterable and joins them into one string, a
string must be specified as separator
S=("Hello","Hi“,"World! “) # the output:
print(“@".join (S)) Hello@Hi@World
9
index(value): finds the first occurrence of the specified value and raises
an exception if the value is not found
T=(1,3,7,8,7,5,4,6,5) # the output:
print(T.index(7)) 2
12
CREATING A FUNCTION
• Examples
def my_function():
print("Hello from a function")
def sum(a,b):
return (a+b)
def small(a,b):
if (a<b):
d=a
else:
d=0
return d
14
CREATING A FUNCTION
• Examples
def Min(a,b):
if (a<b):
return a
else:
return b
def Min(a,b):
if (a<b):
return a
elif (a>b):
return b
else:
s=‘there are equal’
return s
15
CALLING A FUNCTION
• To call a function, use the function name followed by parenthesis and
arguments.
• Function Arguments: You can call a function by using the following
types of formal arguments
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
16
CALLING A FUNCTION
• Required arguments: are the arguments passed to a function in
correct positional order. Here, the number of arguments in the
function call should match exactly with the function definition.
x=2
y=4
print(sum(x,y))
# the output:
6
print(small(2,4))
# the output:
2
x=2
y=4
print(small(x,y))
# or print(small(a=x,b=y))
17
CALLING A FUNCTION
• Keyword arguments: When you use keyword arguments in a function
call, the caller identifies the arguments by the parameter name. This
allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters.
def small(a,b):
if (a<b):
d=a
else:
d=0
return d
print(small(b=2,a=4))
# the output:
0
18
CALLING A FUNCTION
Exercise:
What are the ouputs of the following codes
def Info(name,age):
print ("Name: ",name)
print ("Age ",age)
return
#Now you can call Info function
Info( age=20, name=“Jim" )
Info(‘Marry’,30)
Info(50,40)
19
CALLING A FUNCTION
• Default argument: is an argument that assumes a default value if a
value is not provided in the function call for that argument. The
following example gives an idea on default arguments, it prints default
age if it is not passed.
• All arguments without default values must be listed before arguments
with default values in the function definition.
def Info(name,age=35):
print ("Name: ",name)
print ("Age ",age)
#Now you can call Info function
Info( age=20, name=“Jim" )
Info(‘Mack’)
# the output:
Name: Jim
Age 20
Name: Mack
Age 35
20
CALLING A FUNCTION
Exercise:
What are the ouputs of the following codes
CALLING A FUNCTION
Variable-length arguments:
In addition to named arguments, functions can accept two special
collections of arguments. In Python, we can pass a variable number of
arguments to a function using special symbols. There are two special
symbols:
*args (Non Keyword Arguments)
**kwargs (Keyword Arguments)
The first is a named tuple. This special argument is identified by prefixing it
with a single asterisk (*).
The second is a variable-length dictionary containing all keyword arguments
passed to the function that were not explicitly defined as part of the function
arguments. This argument is identified by prefixing it with two asterisks (**).
22
CALLING A FUNCTION
• Variable-length arguments
# the output:
Name: Mack
Age 24
gender: M
capital letter: ('A', 'B')
23
CALLING A FUNCTION
• Variable-length arguments
def any_function(**K):
print(“Data type of argument:", type(K))
print (‘K:',K)
any_function(type=‘Senior‘,Age=22)
# the output:
Data type of argument: <class 'dict'>
K: {'type': ‘Senior ‘,'Age': 22}
• *args and **kwargs are special keywords which allow function to take variable
length argument.
• *args passes variable number of non-keyworded arguments list and on which
operation of the list can be performed.
• **kwargs passes variable number of keyword arguments dictionary to function on
which operation of a dictionary can be performed.
• *args and **kwargs make the function flexible.
24
CALLING A FUNCTION
Exercise:
What are the ouputs of the following codes
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
def countryISO_code(**code):
print (“ISO codes")
print(code)
return
#Now you can call countryISO_code function
countryISO_code(tn=“Tunisia”,de="German",en="English",fr="French")
25
NESTED FUNCTION
• Python supports the concept of a nested function or inner function, which is
simply a function defined inside another function
• It is important to mention that the outer function has to be called in order for
the inner function to execute. If the outer function is not called, the inner
function will never execute.
def outer():
def outer(): x=5
x=5 def inner():
def inner(): x=10
x=10 print(‘inner’,x)
print(‘inner’,x) return
return inner()
inner() print(‘outer’,x)
print(‘outer’,x) #Now call inner function
#Now call outer function inner()
outer()
# the output:
# the output:
inner 10 # The code will return
outer 5
nothing when executed!
29
NESTED FUNCTION
def outside():
• msg is declared in the outside function and
msg = "Outside!" assigned the value "Outside!".
def inside():
msg = "Inside!" • Then, in the inside function, the value "Inside!" is
assigned to it.
print(msg)
inside()
print(msg)
outside() • When we run outside, msg has the value "Inside!" in
# the output: the inside function, but retains the old value in
Inside!
Outside!
the outside function.
• Python hasn’t assigned to the
existing msg variable, but has created a new
variable called msg in the local scope of inside.
30
NESTED FUNCTION
def outside():
• By adding nonlocal keyword to the top
msg = "Outside!" of inside, Python knows that when it sees an
def inside():
nonlocal msg assignment to msg, it should assign to the
msg = "Inside!"
print(msg) variable from the outer scope instead of
inside()
print(msg)
declaring a new variable.
outside()
# the output:
• The usage of nonlocal is very similar to that
Inside! of global, except that is used for variables in
Inside!
outer function scopes and the latter is used for
variable in the global scope.
31
NESTED FUNCTION
Exercise:
What are the outputs of the following codes
RECURSIVE FUNCTIONS
• Python accepts function recursion.
• 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.
def factorial_recursive(n):
Rules for Recursive function:
if n==1:
return 1 • It must have a base case.
else:
return n*factorial_recursive(n-1) • It must change its state and move
# Now call factorial_recursive toward the base case.
a=3
print(factorial_recursive(a))
print(factorial_recursive(5))
• It must call itself, recursively.
# the output:
6
120
33
RECURSIVE FUNCTIONS
Exercise:
What is the output of the following code
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
print(factorial(5))
34
• Python uses a mechanism, which is known as Call-by-Object, sometimes also called Call
by Object Reference (is the more accurate way of describing it).
• In Python, variables are not passed by reference or by value, they are passed
depends on the object’s type :
If the object is mutable, then modifications to the object will persist
LAMBDA FUNCTION
• In Python, anonymous function is a function that is defined without a name.
• Anonymous functions are defined using the lambda keyword.
• Lambda function does not include a “return” statement, it always contains
an expression which is returned
• Anonymous functions are also called lambda functions.
• A lambda function can take any number of arguments, but can only have
one expression.
lambda arguments: expression
x =lambda a, b, c: a + b + c
print(x(5, 6, 2))
# the output:
13
x=lambda a:a** 2
print(x(5))
# the output:
25
39
• The filter() function in Python offers an elegant way to filter out all the
elements of a sequence and to return a new list which contains items
for which the function evaluates to True.
• The filter() method takes two arguments :
A function - function that tests if elements of an iterable returns true or
false
• Example: use the map() function to double all the items in a list.
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
# the output:
[2, 10, 8, 12, 16, 22, 6, 24]
# the output:
[9, 11, 13]
42
def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
43
• Example:
from functools import reduce
My_list = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), My_list)
print (sum)
# the output:
193
44
MODULES IN PYTHON
• The modules in Python are:
• Built-in modules:
• Contain resources for certain system-specific functionalities such as OS
management, disk IO, etc.
• The standard library also contains many Python scripts (with the .py
extension) containing useful utilities.
• To display a list of all available modules, use the following command:
help(‘modules’)
BUILT-IN MODULES
• The Python interpreter has a number of built-in modules frequently used :
sys Information about Python itself (path, etc.)
platform used to access the underlying platform’s data, such as, hardware,
operating system, interpreter version information.
os Operating system functions
os.path Portable pathname tools
shutil Utilities for copying files and directory trees
cmp Utilities for comparing files and directories
glob Finds files matching wildcard pattern
re Regular expression string matching
time Time and date handling
datetime Fast implementation of date and time handling
doctest, unittest Modules that facilitate unit test
math, cmath Math functions (real and complex) faster for scalars
random Random generators (likewise)
gzip read and write gzipped files
struct Functions to pack and unpack binary data structures
StringIO, cStringIO String-like objects that can be read and written as
files (e.g., in-memory files)
types Names for all the standard Python type
…
48
BUILT-IN MODULES
• Example: Import and use the platform module
import platform
x = platform.system()
print(x)
# the output:
Windows
• Using the dir() and help Functions: There is a built-in function to list all the
function names (or variable names) in a module. The dir() function
• Example: List all the defined names belonging to the platform module
import platform
x = dir(platform)
print(x)
49
BUILT-IN MODULES
• Example: Import and use the os module
import os
print(os.getcwd())
#Returns the current working directory
# the output:
C:\Users\HP\PycharmProjects\MDTutorial
import os
#create a directory
os.mkdir(‘OldDir’)
import time
#The method sleep() from module time suspends execution for the given number of seconds
time.sleep(3)
#rename a file or directory
os.rename(‘OldDir’,’NewDir’)
#delete a directory
os.rmdir(‘NewDir’)
#returns the content of a directory
print(os.listdir())
50
BUILT-IN MODULES
• Example: Import and use the math module
import math
content=dir(math)
print(content)
• Now we can use the module we just created, by using the import statement.
• To access a module’s functions, type “module_name.function_name()”
• Create another python script in the same directory with
name module_test.py and write the following code into it.
import calculation #Importing calculation module
print(calculation.add(1,2)) #Calling function defined in calculation module
# the output:
3
53
# the output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'sub']
54
VARIABLES IN MODULE
• The module can contain functions, as already described, but also
variables of all types (arrays, dictionaries, objects etc)
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)
student = {
"name": “Med",
" level": “freshman",
"age": 19,
"country": “Tunis"}
# the output:
19
57
LOCATING MODULES
• When you import a module named calculation, the interpreter first searches
for a built-in module with that name. If not found, then searches for the
module in the following sequences: :
• The interpreter searches for a file named name.py in the current
directory given by variable sys.path
• If the module isn’t found, then it searches in the list of directories
specified by PYTHONPATH
• If all else fails, Python checks the default path (in UNIX -
.:/usr/local/lib/python, and in Windows c:\python20\lib)
• Script being run should not have the same name as a standard module or
an error will occur when the module is imported
59
PACKAGES IN PYTHON
• Similar, as a directory can contain sub-directories and files, a
Python package can have sub-packages and modules.
PACKAGES IN PYTHON
• Example: Suppose we are developing a game, one possible
organization of packages and modules could be as shown in the
figure below.
IMPORTING MODULES FROM PACKAGE
• We can import modules from packages using the dot (.) operator.
Examples:
• If want to import the start module in the above example, it is done as follows.
import Game.Level.start
• we can import the module without the package prefix and call the function simply:
from Game.Level import start
start.select_difficulty_level(2)
• Another way of importing just the required function (or class or variable) form a
module within a package and then we can directly call this function :
from Game.Level.start import select_difficulty_level
select_difficulty_level(2)
PACKAGES AND MODULES
The main difference between a module and a package is that a package is a
collection of modules AND it has an __init__.py file.
myMath/ # add.py
__init__.py
def add(x, y): # sqrt.py
adv/
"""""" import math
__init__.py
sqrt.py return x + y
def squareroot(n):
add.py
""""""
subtract.py
return math.sqrt(n)
multiply.py
divide.py
CONGRATULATIONS