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

Updated Python Unit

Uploaded by

its me Lofy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Updated Python Unit

Uploaded by

its me Lofy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Python Programming

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):

Argument to pass a value in colon(:) to mark end of


function function header

5
Types of Functions
• Build-in functions :
Functions that are built Example: print(), input(), eval().
into python.

Example: def my_adition(x,y):


• User-defined
Functions: Functions sum = x+y
defined by users return sum
themselves.

7
Creating a Function in Python

• We can create a user-defined function in Python, using the def keyword. We


can add any type of functionalities and properties to it as we require.
• # A simple Python function

• 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")

# Driver code to call a function


fun()
10
Example:
def greet():
print('Hello 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)

# function call with no value


add_numbers()
Python Function Arguments
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)
# Output: Sum: 9
Default argument

Example: def printme(name,age=22):


print("My name is",name,"and age
is",age)
• A default argument is a printme(name = "john")
parameter that assumes
a default value if a value Output: My name is john and age is 22

is not provided in the


function call for that
argument.

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

# function call with no arguments


add_numbers()
Keyword arguments

Example: def func(fname, lname):


print("Hi "+ fname + " " + lname)
When we call a function with
func(lname=“Yadav", fname=“Priyanka")
some values, these values get
assigned to the arguments
Output: Hi Priyanka Yadav
according to their position.

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

def nameAge(name, age): print("Case-1:")


print("Hi, I am", name) nameAge("Suraj", 27)
print("My age is ", age) # You will get incorrect output
because

# You will get correct output because # argument is not in order

# argument is given in order print("\nCase-2:")


nameAge(27, "Suraj")
Python Function With Arbitrary Arguments

• Sometimes, we do not know in advance the number of arguments that will


be passed into a function. To handle this kind of situation, we can use
arbitrary arguments in Python.
• Arbitrary arguments allow us to pass a varying number of values during a
function call.
• We use an asterisk (*) before the parameter name to denote this kind of
argument.
Program to find sum of multiple numbers
def find_sum(*numbers): # function call with 3 arguments
result = 0 find_sum(1, 2, 3)

for num in numbers: # function call with 2 arguments


result = result + num find_sum(4, 9)
print("Sum = ", result)
Python Function within Functions
• # Python code to show how to access variables of a nested functions
• # defining a nested function
• def word():
• string = 'Python functions tutorial'
Output:
• x=5 Python functions tutorial
• def number(): 5
• print( string )
• print( x )
• number()
• word()
Return Statement in Python Function
• A Python function may or may not return a value. If we want our function to return some
value to a function call, we use the return statement. For example,
def add_numbers():
...
return sum
• Here, we are returning the variable sum to the function call.
• The return statement also denotes that the function has ended. Any code after return is not
executed.
Find Square of a number
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)

print('Square:',square)

# Output: Square: 9
Example:

# function that adds two numbers


def add_numbers(num1, num2):
sum = num1 + num2
return sum
Output:
Sum: 9
# calling function with two values
result = add_numbers(5, 4)

print('Sum: ', result)


Return Multiple Values
• def arithmetic(num1, num2): • # read four return values in four
variables
• add = num1 + num2
• sub = num1 - num2 • a, b, c, d = arithmetic(10, 2)
• multiply = num1 * num2
• division = num1 / num2 • print("Addition: ", a)
• # return four values • print("Subtraction: ", b)
• return add, sub, multiply, division • print("Multiplication: ", c)
• print("Division: ", d)
Output

• 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

# Python code to demonstrate scope and num = 10


lifetime of variables
number()
#defining a function to print a number.
print( "Value of num outside the
def number( ): function:", num)
num = 50 Output:
print( "Value of num inside the
function: ", num)
Value of num inside the function: 50
Value of num outside the function: 10
Python Global Keyword
• In Python, the global keyword allows us to modify the variable outside of the
current scope.
• It is used to create a global variable and make changes to the variable in a
local context.
• we can only access the global variable but cannot modify it from inside the
function.
• The solution for this is to use the global keyword.
Access and Modify Python Global Variable

c = 1 # global variable # global variable


c=1
def add():
def add():
# increment c by 2
print(c)
c=c+2
add() print(c)
add()
# Output: 1 Output: error
Example: Changing Global Variable From Inside a
Function using global keyword
# global variable # increment c by 2
c=1 c=c+2

def add(): print(c)

# use of global keyword add()


global c
# Output: 3
Rules of global Keyword

• The basic rules for global keyword in Python are:

• When we create a variable inside a function, it is local by default.


• When we define a variable outside of a function, it is global by default.
You don't have to use the global keyword.
• We use the global keyword to read and write a global variable inside a
function.
• Use of the global keyword outside a function has no effect.
Swap value using function
def swap(x, y):
temp = x
x=y
y = temp
# Driver code
x=2
y=3
swap(x, y)
print(x)
print(y)
Write a Python function to find the maximum
of three numbers.
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
Write a Python function to multiply all the
numbers in a list.
def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7))) // output: -336
Write a Python function that takes a number as a parameter
and checks whether the number is prime or not.

def test_prime(n): else:


if (n==1): for x in range(2,n):
return False if(n % x==0):
elif (n==2): return False
return True; return True
print(test_prime(9))
Recursive Function
• A recursive function is a function that calls itself, again and again.
• Consider, calculating the factorial of a number is a repetitive activity, in that
case, we can call a function again and again, which calculates factorial.
Recursive function
to find the factorial of an integer
• factorial(5) def factorial(x):

• 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

• In Python, an anonymous function means that a function is without a name.


the lambda keyword is used to create anonymous functions.
• Syntax:
• lambda [argument1 [argument2... .argumentn]] : expression
• argument(s) - any value passed to the lambda function
• expression - expression is executed and returned
Lambda function rules

• 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()

add = lambda x: x+2


Print(add(5))
• # Output: Hello World
• 7
lambda function with arguments
# Python code to demonstrate anonymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;

# Calling the function and passing values


print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )
Example:

• #multiply 2 numbers
• a = lambda x, y : (x * y)
• print(a(4, 5))

• #add multiple numbers


• a = lambda x, y, z : (x + y + z)
• print(a(4, 5, 5))
What's the Distinction Between Lambda and
Def Functions?
• # Code to demonstrate how we can • # code using the function defined
use a lambda function for adding 4 by def keyword
numbers • def add( num ):
• add = lambda num: num + 4 • return num + 4
• print( add(6) ) • print( add(6) )
• Output: • Output:
• 10 • 10
Python Modules
What is Modular Programming?
• As our program grows bigger, it may contain many lines of code. Instead of
putting everything in a single file, we can use modules to separate codes in
separate files as per their functionality. This makes our code organized and
easier to maintain.

• Module is a file that contains code to perform a specific task. A module may
contain variables, functions, classes etc.
Modularizing benefits.

• Simplification: A module often concentrates on one comparatively small area of


the overall problem instead of the full task. We will have a more manageable design
problem to think about if we are only concentrating on one module. Program
development is now simpler and much less vulnerable to mistakes.
• Flexibility: Modules are frequently used to establish conceptual separations
between various problem areas. It is less likely that changes to one module would
influence other portions of the program if modules are constructed in a fashion
that reduces interconnectedness. (We might even be capable of editing a module
despite being familiar with the program beyond it.) It increases the likelihood that a
group of numerous developers will be able to collaborate on a big project.
Continue…
• Reusability: Functions created in a particular module may be readily
accessed by different sections of the assignment (through a suitably
established api). As a result, duplicate code is no longer necessary.
• Scope: Modules often declare a distinct namespace to prevent identifier
clashes in various parts of a program.
• In Python, modularization of the code is encouraged through the use of
functions, modules, and packages.
What are Modules in Python?
• A document with definitions of functions and various statements written in
Python is called a Python module.
In Python, we can define a module as:
• User defined module
• Build in module
Create a module
# def square( number ): • save it as smodule.py.
# here, the above function will squa
re the number passed as the input
result = number ** 2
return result # here, we are retu
rning the result of the function
How to Import Modules in Python?
• we may import functions from one // access function
module into our program, or as we module_name.function_name()
say into, another module.
• we make use of the import Python
keyword.
Syntax:
• import module_name
Example: import smodule
import smodule
# here, we are calling the module square method and passing the value 4
result = smodule.square( 4 )
print("By using the module square of number is: ", result )
Import Python Standard Library
Modules(build-in)
• The Python standard library contains # import standard math module
well over 200 modules. We can import
import math
a module according to our needs.

# use math.pi to get value of pi


• Suppose we want to get the value of
pi, first we import the math module print("The value of pi is", math.pi)
and use math.pi. For example,
Python Built-in modules
# importing built-in module math # 60 degrees = 1.04 radians
import math print(math.radians(60))
# using square root(sqrt) function contained
# in math module # Sine of 2 radians
print(math.sin(2))

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

• # display the calendar


• print(calendar.month(yy, mm))
random module
# import standard math module • Print(r1)
import random
• Output:
# use random module to print • 7
random number
r1 = random.randint(5, 15)
Printing a random value from a list, string and
tuple in Python
# import random # prints a random item from the tuple
import randimport random
tuple1 = (1, 2, 3, 4, 5)
print(random.choice(tuple1))
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6] Output:
print(random.choice(list1)) 2
e
# prints a random item from the string
1
string = "geeks"
print(random.choice(string))
Python import with Renaming
• # import module by renaming it • We have renamed the math module
• import math as m as m. This can save us typing time
in some cases.

• 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

• To import all the objects from a from math import *


module within the present print(pow(2,2))
namespace, use the * symbol and
the from and import keyword. print(factorial(5))
• Syntax:
print(pi*3)
• from name_of_module import * print(sqrt(100))
Python Module Search Path
• When we import any program module, the interpreter first searches for a specified
name for a built-in module. If the name is not found, the interpreter searches in a
list of directories given by the variable sys.path which initialized from the
environment variable PYTHONPATH.

• 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):

print("Hello ", name) return 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.

• >>> from mypackage import functions


• >>> functions.power(3,2)
• 9
import specific functions from a module in the
package.

• >>> from mypackage.functions import sum


• >>> sum(10,20)
• 30
• >>> average(10,12)
• Traceback (most recent call last):
• File "<pyshell#13>", line 1, in <module>
• NameError: name 'average' is not defined
Understanding __init__.py
• __init__.py helps the Python interpreter recognize the folder as a package.
• It also specifies the resources to be imported from the modules.
• If the __init__.py is empty this means that all the functions of the modules
will be imported. We can also specify the functions from each module to be
made available.
Modify __init__.py
• from .functions import average, power
• from .greet import SayHello
Test mypackage
Create test.py in the MyApp folder to test mypackage.
from mypackage import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2) : ", x) Hello world
power(3,2) : 9
Fibonacci series
def fibo(n):
if n <= 1: if n<= 0:
return n print("Plese enter a positive int
else: eger")
return(fibo(n-1) + fibo(n-2)) else:
# take input from the user print("Fibonacci sequence:")
n = int(input("How many terms? ")) for i in range(n):
# check if the number of terms is valid print(fibo(i))
Armstrong number

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

def simple_interest(p,t,r): simple_interest(8, 6, 8)


print('The principal is', p) Output:
print('The time period is', t) The principal is 8
print('The rate of interest is',r) The time period is 6
• si = (p * t * r)/100
The rate of interest is 8
• print('The Simple Interest is', si)
The Simple Interest is 3.84
• return si
Python Program to find volume, surface
area of a cuboid
import math • # function to find the volume
# function to calculate
# Surface area • def find_volume(l, b, h):
def find_surafce_area(l, b, h):

• # formula to calculate
# formula of surface_area = 2(lb + bh + hl)
• # volume = (l * b*h)
Surface_area = 2 * ( l * b + b * h + h * l)
• Volume = (l * b * h)
print(Surface_area)
• print(Volume)
# Driver Code Outpot:
l=9
408
b=6
h = 10
540
# surface area
# function call
find_surafce_area(l, b, h)
# volume function call
find_volume(l, b, h)

You might also like