03 Python Functions
03 Python Functions
3. Python Functions
Python Functions
def function_name(parameters):
"""docstring"""
statement(s)
return val #optional
Above shown is a function definition that consists of the following components.
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
print(absolute_value.__doc__)
Function Example: Selection Sort
def sort(A):
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in
# remaining unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the found minimum element
# with the first element
A[i], A[min_idx] = A[min_idx], A[i]
return(A)
greet("Ahmad")
greet("Mohmd", "How do you do?")
# 2 keyword arguments
greet(name = "Ahmad", msg = "How do you do?")
def greet(*names):
"""This function greets all
the person in the names tuple."""
num = 5
print("The factorial of", num, "is", factorial(num))
Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.
def recursor():
recursor()
recursor()
Advantages of Recursion
Disadvantages of Recursion
Lambda functions can have any number of arguments but only one
expression
print(multiply(5,6))
Python Anonymous/Lambda Function
print(new_list)
print(new_list)
outer()
Python Global, Local and Nonlocal variables
def outer_function(): def outer_function(): def outer_function():
a = 20 global a #global a
a = 20 #a = 20
def inner_function():
a = 30 def inner_function(): def inner_function():
print('a =', a) global a #global a
a = 30 #a = 30
inner_function() print('a =', a) print('a =', a)
print('a =', a)
inner_function() inner_function() Read
Only
print('a =', a) print('a =', a)
a = 10
outer_function()
print('a =', a) a = 10 a = 10
outer_function() outer_function()
print('a =', a) print('a =', a)
def bar():
global x
x = 25
foo()
print("x in main: ", x) Output:
Before calling bar: 20
Calling bar now
After calling bar: 20
x in main: 25
Global Variables Across Python Modules
In Python, we create a single module config.py to hold global variables and share information across Python
modules within the same program.
config.py main.py
a = 0 import config
b = "empty" import update
print(config.a)
print(config.b)
update.py
import config
config.a = 10
config.b = "alphabet"
Python Modules
Modules refer to a file containing Python statements and definitions.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
example.py main.py
# Python Module example import example
print(example.add(4,5.5))
def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result
Python Modules
Import with renaming
# import module by renaming it
import math as m
print("The value of pi is", m.pi)
import my_module
This code got executed
import my_module
import my_module
Reloading a module
import imp
import my_module
This code got executed
import my_module
imp.reload(my_module)
This code got executed
The dir() built-in function
We can use the dir() function to find out names that are defined inside a module.
example.py
print(add(5,9))
import example
dir(example)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', 'add’]
example.__name__
'example'
Python Package
• As our application program grows larger in size with a lot of modules, we place similar modules in one package
and different modules in different packages. This makes a project (program) easy to manage and conceptually
clear.
• Python package can have sub-packages and modules.
• A directory must contain a file named __init__.py in order for Python to consider it as a package. This file
can be left empty but we generally place the initialization code for that package in this file.
If this construct seems lengthy, we can import the module without the
package prefix as follows:
from Game.Level import start
Or:
from Game.Level.start import select_difficulty
select_difficulty(2)
Python Package
There are 2 main reasons for __init__.py
1- For convenience: the other users will not need to know your functions' exact location in your package
your_package/
__init__.py # in __init__.py
file1.py from file1 import *
file2.py
from file2 import *
...
fileN.py ...
from fileN import *