Updated Python Unit
Updated Python Unit
Unit 3
Unit 3
3. Python Functions, Modules and Packages
Introduction to Unit
Organizing python codes using functions
Organizing python projects into modules
Import own module as well as external modules
Understanding Packages
Lamda function in python
Programming using function, modules and external
pakages
Conclusion of Unit
Function in Python
• Function is a group of related statements that perform
a specific task.
• Functions help break our program into smaller and
modular chucks.
• The idea is to put some commonly or repeatedly done tasks
together and make a function so that instead of writing the same
code again and again for different inputs, we can do the function
calls to reuse code contained in it over and over again.
3
Advantage of Function
• By using functions, we can avoid rewriting same logic/code
again and again in a program.
• We can call python functions any number of times in a
program and from any place in a program.
• Increase Code Readability
• Increase Code Reusability
4
Defining Functions
def marks the start of function.
function name the uniquely identify a
function.
def function_name(parameter):
5
Types of Functions
• Build-in functions :
Functions that are built Example: print(), input(), eval().
into python.
7
Creating a Function in Python
• def fun():
• print("Welcome to world")
How function works
• When the function is called, the control
of the program goes to the function
definition.
• All codes inside the function are
executed.
• The control of the program jumps to
the next statement after the function
call.
Function calling
After creating a function in Python we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.
# A simple Python function
def fun():
print("Welcome to world")
Output:
# call the function Hello World!
Outside function
greet()
print('Outside function')
Function Arguments
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma. # function
with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
Function call with arguments
If we create a function with arguments, we need to pass the corresponding
values while calling them. For example,
# function call with two values
add_numbers(5, 4)
16
Example:
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3) Output:
Sum: 5
# function call with one argument Sum: 10
add_numbers(a = 2) Sum: 15
18
Positional Arguments
• We used the Position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or value)
is assigned to age.
• By changing the position, or if you forget the order of the positions, the
values can be used in the wrong places, where 27 is assigned to the name and
Suraj is assigned to the age.
Example
print('Square:',square)
# Output: Square: 9
Example:
• Addition: 12
• Subtraction: 8
• Multiplication: 20
• Division: 5.0
Scope Rules
A variable defined inside a function cannot be accessed outside it. Every
variable has a well-defined accessibility.
• A variable can have one of the following two scopes:
Global Variable: In Python, a variable that is defined outside any function or any block
is known as a global variable. This means that a global variable can be accessed
inside or outside of the function.
Local Variable: A variable that is defined inside any function or a block is known as
a local variable.
29
Example
• if x == 1:
return 1
• 5*factorial(4)
else:
• 5*4*factorial(3) return (x * factorial(x-1))
• 5*4*3*factorial(2) num = 5
• 5*4*3*2*factorial(1) print("The factorial of", num, "is", factorial(num))
• 5*4*3*2*1 = 120
The advantages/disadvantage of the
recursive function:
• advantages • disadvantage
• By using recursive, we can reduce • The recursive function takes more
the length of the code. memory and time for execution.
• The readability of code improves • Debugging is not easy for the
due to code reduction. recursive function
• Useful for solving a complex
problem
Anonymous/lambda Functions in Python
• This function can have any number of arguments but only one
expression, which is evaluated and returned.
• One is free to use lambda functions wherever function objects are
required.
• You need to keep in your knowledge that lambda functions are
syntactically restricted to a single expression.
• It has various uses in particular fields of programming, besides other
types of expressions in functions.
Example
• # declare a lambda function
• greet = lambda : print('Hello World')
• #Call
• greet()
• #multiply 2 numbers
• a = lambda x, y : (x * y)
• print(a(4, 5))
• Module is a file that contains code to perform a specific task. A module may
contain variables, functions, classes etc.
Modularizing benefits.
print(math.sqrt(25))
# 2 radians = 114.59 degrees
print(math.degrees(2))
# using pi function contained in math
module
print(math.pi)
Displaying a Calendar for a Month in
Python
• # import module
• import calendar
• yy = 2023
• mm = 4
• print(m.pi)
• Note that the name math is not
recognized in our scope. Hence,
• # Output: 3.141592653589793 math.pi is invalid, and m.pi is the
correct implementation.
Python from...import statement
• # import only pi from math
module
• from math import pi
• print(pi)
• # Output: 3.141592653589793
Importing Multiple Modules in Python
• Importing multiple modules using a single from keyword is not possible. We
need to use multiple from keywords to import multiple modules.
from hello import greet
from math import sqrt
greet()
print(sqrt(4)) //output: nice to meet you
2.0
Import all Names - From import * Statement
• PYTHONPATH have the same syntax as the Unix shell variable PATH, list of the
colon(:)-separated directory names. When a PYTHONPATH is not set, or the file is
not found there, the search continues in an installation-dependent default path. It is
usually /usr/local/lib/python.
Python Package
• Python modules may contain several classes, functions, variables, etc. whereas
Python packages contain several modules. In simpler terms, Package in
Python is a folder that contains various modules as files.
• A package is a container that contains various functions to perform specific
tasks. For example, the math package includes the sqrt() function to perform
the square root of a number.
• While working on big projects, we have to deal with a large amount of code,
and writing everything together in the same file will make our code look
messy. Instead, we can separate our code into multiple files by keeping the
related code together in packages.
• Now, we can use the package whenever we need it in our projects. This way
we can also reuse our code.
Creating Package
• Let's create a package named mypackage
• Create a new folder named D:\MyApp.
• Inside MyApp, create a subfolder with the name 'mypackage'.
• Create an empty __init__.py file in the mypackage folder.
• Using a Python-aware editor like IDLE, create modules greet.py and
functions.py
Create module
greet.py function.py
def SayHello(name): def sum(x,y):
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
Importing a Module from a Package
• Now, to test our package, navigate the command prompt to the MyApp folder and invoke
the Python prompt from there.
• D:\MyApp>python
• Import the functions module from the mypackage package and call its power() function.
def check_armstrong(n):
digits = len(str(num))
sum_of_digits = 0
for digit in digits:
sum_of_digits = sum_of_digits +int (digit) **num_digit
return sum_of_digits== n
print(check_Armstrong(370))
# Python3 program to find simple interest