Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views

03 Python Functions

The document discusses Python functions. It describes the components of a function definition including the def keyword, function name, parameters, colon, optional docstring, statements, optional return statement, and return value. It provides examples of defining, calling, and documenting functions. It also covers function types, arguments, recursion, anonymous functions, global and local variables, and modules.

Uploaded by

649f6c4a3b
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

03 Python Functions

The document discusses Python functions. It describes the components of a function definition including the def keyword, function name, parameters, colon, optional docstring, statements, optional return statement, and return value. It provides examples of defining, calling, and documenting functions. It also covers function types, arguments, recursion, anonymous functions, global and local variables, and modules.

Uploaded by

649f6c4a3b
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PYTHON

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.

1. Keyword def that marks the start of the function header.


2. A function name to uniquely identify the function. Function naming follows the same
rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements
must have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Function Example
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""

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)

list = [42, 16, 84, 12, 77, 26, 53]


print(sort(list))
Types of Functions

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

Python Function Arguments


def greet(name, msg):
"""This function greets to
the person with the provided message"""
print("Hello", name + ', ' + msg)

greet("Ahmad", "Good morning!")


Variable Function Arguments

Three different forms of this type:


Python Default Arguments
def greet(name, msg="Good morning!"):
""" This function greets to the person with the provided message.
If the message is not provided, it defaults to "Good morning!" """

print("Hello", name + ', ' + msg)

greet("Ahmad")
greet("Mohmd", "How do you do?")

Non-default arguments cannot follow default arguments


def greet(msg = "Good morning!", name):
Python Keyword Arguments

We can call the previous function in different ways

# 2 keyword arguments
greet(name = "Ahmad", msg = "How do you do?")

# 2 keyword arguments (out of order)


greet(msg = "How do you do?", name = "Ahmad")

# 1 positional, 1 keyword argument


greet("Ahmad", msg = "How do you do?")
Python Arbitrary Arguments
Sometimes, we do not know the number of arguments that will be passed into a
function. We use an asterisk (*) before the parameter name

def greet(*names):
"""This function greets all
the person in the names tuple."""

# names is a tuple with arguments


for name in names:
print("Hello", name)

greet("Ahmad", "Mohmd", "Samer", "Saleem")


Python Recursion
Recursion is the process of defining something in terms of itself.

Example: factorial of an integer


def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 5
print("The factorial of", num, "is", factorial(num))

For example, the factorial of 6 (6!) is 1*2*3*4*5 = 120


Python Recursion

factorial(3) # 1st call with 3


3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
Python Recursion

Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.

The Python interpreter limits the depths of recursion to help avoid


infinite recursions, resulting in stack overflows.

By default, the maximum depth of recursion is 1000. If the limit is


crossed, it results in RecursionError. Example:

def recursor():
recursor()
recursor()
Advantages of Recursion

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.

Disadvantages of Recursion

1. Sometimes the logic behind recursion is hard to follow through.


2. Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
3. Recursive functions are hard to debug.
Python Program for Tower of Hanoi
Python Program for Tower of Hanoi
Python Anonymous/Lambda Function

In Python, an anonymous function is a function that is defined without a


name.

Anonymous functions are defined using the lambda keyword.

Lambda functions can have any number of arguments but only one
expression

Example: multiply = lambda a, b: a * b

print(multiply(5,6))
Python Anonymous/Lambda Function

Example use with filter()


The filter() function in Python takes in a function and a list as
arguments and returns a new list.

# Program to filter out only the even items from a list


my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)

Output: [4, 6, 8, 12]


Python Anonymous/Lambda Function

Example use with map()


The map() function in Python takes in a function and a list.
The function is called with all the items in the list. A new list is returned
which contains items returned by that function for each item.
# Program to double each item in a list using map()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

print(new_list)

Output: [2, 10, 8, 12, 16, 22, 6, 24]


Python Global, Local and Nonlocal variables

Global Variables Local Variables Nonlocal Variables

x = "this is global" def foo(): def outer():


y = "this is local" x = "local"
def foo(): print(y)
print("x inside:", x) def inner():
foo() nonlocal x
x = "nonlocal"
foo() print(y) print("inner:", x)
print("x outside:", x)
inner()
print("outer:", x)

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)

Output: Output: Output:


a = 30 a = 30 a = 10
a = 20 a = 30 a = 10
a = 10 a = 30 a = 10
Global in Nested Functions
def foo():
x = 20

def bar():
global x
x = 25

print("Before calling bar: ", x)


print("Calling bar now")
bar()
print("After calling bar: ", x)

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)

Python from...import statement

# import only pi from math module

from math import pi


print("The value of pi is", pi)

Import all names

# import all names from the standard module math

from math import *


print("The value of pi is", pi)
Python Modules
The Python interpreter imports a module only once during a session
# This module shows the effect of
# multiple imports and reload

print("This code got executed")

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

def add(a, b):


result = a + b
return result

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.

Here is an example. Suppose we are


developing a game. One possible
organization of packages and modules
could be as shown in the figure.
Python Package
Importing module from a package

To import the start module in the example


import Game.Level.start

Now, if this module contains a function named


select_difficulty(), we must use the full name to reference it.
Game.Level.start.select_difficulty(2)

If this construct seems lengthy, we can import the module without the
package prefix as follows:
from Game.Level import start

We can now call the function simply as follows:


start.select_difficulty(2)

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 *

then others can call add() by # in file1.py


from your_package import add def add():
without knowing file1, like pass
from your_package.file1 import add

2- If you want something to be initialized;


for example, logging (which should be put in the top level)

You might also like