108443 – Introduction to
Information Technology
Functions & Modules
Note:- some material of the course has been adopted from freely available public sources
12/28/2024
Intro
A function is a group of related statements that performs a
specific task.
Functions help break our program into smaller and
modular chunks. As our program grows larger and larger,
functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code
reusable.
A function is a block of code which only runs when it is
called. You can pass data, known as parameters, into a
function. A function can return data as a result
2 12/28/2024
Built-in Functions
We don’t need to define them
You have seen many functions already
Type casting functions: int(), float(), bool(), str()
Get type of a value: type()
Exit function: exit()
Full list can be referenced @
[https://docs.python.org/3/library/functions.html]
3 12/28/2024
Some Examples of Built-in Functions
4 12/28/2024
Some Examples of Built-in Math Functions
5 12/28/2024
Why Functions?
Creating a new function gives you an opportunity
to name a group of statements, which makes your
program easier to read and debug.
Functions can make a program smaller by
eliminating repetitive code. Later, if you make a
change, you only need to make it in one place.
Well-designed functions are often useful for many
programs. Once you write and debug one, you can
reuse it.
6 12/28/2024
Function Syntax
7 12/28/2024
Creating/defining a Function
8 12/28/2024
Number of Arguments
By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you
must call the function with 2 arguments, not more, and not less.
This function expects 2 arguments, and gets 2 arguments:
If you try to call the function with 1 or 3 arguments, you will get an
error.
9 12/28/2024
Default Argument/Parameter Value
The following example shows how to use a default
parameter value.
If we call the function without argument, it uses
the default value:
10 12/28/2024
Fruitful Functions and Void Functions
Some functions, such as the math functions,
return results; those can be called fruitful
functions.
Other functions, which don’t return a value. They
can be called void functions.
11 12/28/2024
Void Function
Defining a
function
Calling a
function
Avoid having a variable and a function with the
same name
Empty parentheses after the name indicates
function doesn’t take any arguments
12 12/28/2024
Fruitful Function
13 12/28/2024
The return Statement
14 12/28/2024
Example of return (Absolute Value)
15 12/28/2024
Return Multiple Values
16 12/28/2024
How Function works in Python
17 12/28/2024
Class Tasks
Write a function named “average()” that takes three integers as input and returns the
average of the three numbers.
Write a function named “area_circle()” that takes the radius of a circle as input and
returns the area of the circle.
Write a function named “slope()” that takes the X and Y coordinates of two points on a
line as input and returns the slope of the line: 𝑦2 − 𝑦1 = 𝑚 ( 𝑥2 − 𝑥1 ).
Write a function named “isEven()” that takes a positive integer as input and returns 1 if
the number is even and returns 0 if the number is odd
Write a function named “factorial()” that takes a positive integer as input and returns
the
factorial of the input number.
18 12/28/2024
Scope and Lifetime of Variables
Global and nonlocal keywords
Try to limit the global variables in program, global
variables can be accessed and modified anywhere,
and this may result in unexpected behavior’s
Variables declared within a function are scoped
only to that function – called Local Variables
Local Variables are not accessible/ visible outside
of that function
19 Ref:- Ch12: A beginner's’ Guide to Python 3 programming 12/28/2024
Example: Local Variable
20 Ref:- Ch12: A beginner's’ Guide to Python 3 programming 12/28/2024
Example: Global Variable & global Keyword
100
101
101
21 Ref:- Ch12: A beginner's’ Guide to Python 3 programming 12/28/2024
Example: Non-Local Variable & nonlocal Keyword
22 Ref:- Ch12: A beginner's’ Guide to Python 3 programming 12/28/2024
Modules
A python file - can have functions, variables, classes &
executable code
To access a module, use the import command:
import <module name>
Can then access functions like this:
<module name>.<function name>(<arguments>)
Example:
>>> import math
>>> math.cos(2.0)
-0.4161468365471424
23
Reference: Ch 25 of (A beginner guide To Python 3…) Book 12/28/2024
Modules Variables
Modules can have variables, too
Can access them like this:
<module name>.<variable name>
Example:
>>> import math
>>> math.pi
3.141592653589793
24 12/28/2024
Modules Help
After importing a module, can see what functions
and variables are available with:
help(<module name>)
25 12/28/2024
Modules (Online Help)
26 12/28/2024
Some of Frequently Used built-in Modules
io
Read/write from files
random
Generate random numbers
Can pick any distribution
string
Useful string functions
27 12/28/2024
User Created Module
28 12/28/2024
Importing and Using of Modules
Multiple Modules can be imported in single line
Import module1, module2, module3
We can avoid the module name in prefix like
math.pi by importing it as directly available
from <module name> import *
However, it can result in name clashesMay ignore
for now
We can also import a specific feature only
from <module name> import <feature name>
29 12/28/2024
Importing and Using of Modules
We can give an alias for a module being imported
import <module_name> as <alternative_module_name>
We can also give an alias for an element being imported
from a module
from <module_name> import <element> as <alias>
May ignore
for now
30 12/28/2024
Hiding Some Elements of a Module
Any element in a module starts with an underbar
('_') is hidden when a wildcard import of the
contents of a module is performed.
31 12/28/2024
Hiding Some Elements of a Module
However, if we explicitly import the function then
we can still reference it:
To limit the scope of animport to a function; use
it in the body of function
32 12/28/2024
Lambda Function
A lambda function is an anonymous
function (i.e., defined without a name)
that can take any number of arguments
But, unlike normal functions, evaluates
and returns only one expression.
Syntax
lambda parameters : expression
33 12/28/2024
Examples
1. Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
2. Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
3. Sum argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
4. Calculate the length of each word in the tuple:
def myfunc(n):
return len(n)
x = map(myfunc, ('apple', 'banana', 'cherry’))
x = map(lambda x:len(x),
('apple', 'banana', 'cherry'))
34 Python Lambda (w3schools.com) 12/28/2024
Creation & Immediate Execution
We can execute the lambda function
immediately after its creation and receive the
result.
print((lambda x: x + 1)(2))
print((lambda x, y, z: x + y + z)(3, 8, 1))
print((lambda x: x if(x > 10) else 10)(5))
print((lambda x: x if(x > 10) else 10)(12))
If multiple conditions are present (if-elif-...-else), we must
nest them:
(lambda x: x * 10 if x > 10 else (x * 5 if x < 5 else x))(11)
35 12/28/2024