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

Jcs2201-Python Programming Unit-IV Notes

The document covers Unit IV on Functions, Modules, and Packages in Python, detailing the definition, types, and usage of functions, including built-in and user-defined functions, as well as various argument types. It also explains variable scope, recursion, and lambda functions, along with date and time methods using the datetime module. Key concepts include function parameters, return values, and the distinction between local and global variables.

Uploaded by

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

Jcs2201-Python Programming Unit-IV Notes

The document covers Unit IV on Functions, Modules, and Packages in Python, detailing the definition, types, and usage of functions, including built-in and user-defined functions, as well as various argument types. It also explains variable scope, recursion, and lambda functions, along with date and time methods using the datetime module. Key concepts include function parameters, return values, and the distinction between local and global variables.

Uploaded by

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

j

UNIT-IV FUNCTIONS, MODULES AND PACKAGES

Functions: Types, parameters, arguments: positional arguments, keyword arguments, parameters with
default values, functions with arbitrary arguments, Scope of variables: Local and global scope, Recursion
and Lambda functions. Date and Time Methods. Modules and Packages.

1. FUNCTION
1.1 FUNCTIONS
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of codereusing.
Two main advantages of functions are:
(a) They help us to divide our program into multiple tasks. For each task we can define a
function. This makes the code modular.
(b) Functions provide a reuse mechanism. The same function can be called any no. of times.
1.2 TYPES OF PYTHON FUNCTIONS:
(a) Built-in functions – Example. len( ), sorted( ) , min( ), max( ) etc…
(b) User-defined functions.

1.2.1 PRE DEFINED FUNCTIONS


It is also called as built-in functions. These functions are designed & developed by software
provider. We can only able to use not able to modify them. There are 68 built-in functions.

Let us discuss few built in functions with example.


j
j
j
j

1.2.2 USER DEFINED FUNCTIONS


Creating our own functions are called user-defined functions.
➢ Rules to define a function
• Use the def keyword with the function name to define a function.
• Function must end with colon ( : ).
• Next, pass the number of parameters as per your requirement. (Optional).
• Next, define the function body with a block of code. The action you want to perform.
• Finally function will have return a value. (Optional)
Syntax:
def function_name(parameter1, parameter2):
# function body
# write some action
return value
Example:- def fun( n1, n2):
Str=”Hi” print(“Function
Body”)return Str
➢ Calling a function
Calling a function using the function name, parenthesis (opening and closing) and
parameter(s).
Syntax: function_name(arg1, arg2)
Example: fun(“Tom”, ”Jerry”)
➢ Example program to print a string using function.
L1. def fun(n1,n2):
L2. str=’Hi’
L3. print(“Function Body”)L4.
return (n1+’&’+n2) L5.n1, n2
= ‘Tom’, ‘Jerry’
L6. ans = fun(n1,n2)L7.
print(ans)

Output
Function Body

Tom & Jerry


j

Explanation:
Lines 1-3 : Details (definition) of the function.Line
4: Return the value.
Line 5 : Start of main program and variable initialization Line 6 :
Calling a function by passing arguments n1 and n2.Line 7 : Print
the return value. (That is Tom & Jerry)

Example 2: Following figure shows addition of two numbers.

1.3. ACTUAL & FORMAL PARAMETERS OR ARGUMENTS:


Actual parameters:
o When a function is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument.
o In the above example: 2, 4 are actual parameters/values
Formal parameters:
➢ The variables defined in the function header are known as formal parameters.
➢ In the above example: num1, num2 are formal parameters
j

2.ARGUMENTS
Types of arguments in functions
There are four types of arguments.
(i) Required Arguments
(ii) Keyword Arguments
(iii) Default Arguments
(iv) Variable-Length arguments
2.1 Required Arguments
These arguments are passed to a function in correct positional order. Here the number of
arguments in the function call should match exactly with the function definition.

#Program1 #Program2
def printme(t,str): def printme():
print("Temparature =%d" %t) print("Temparature =%d" %str)
print(str) print(t)
return return
temp=40 temp=40
label='Its very sunny, cannot play cricket' label='Its very sunny, cannot play cricket'
printme(temp,label) printme(temp,label)

Temparature = 40 Traceback (most recent call last):


Its very sunny, cannot play cricket File "E:\Jerusalem College\Academic_Year\Jan2023-
June2023\PythonProgramming\Programs\functions.py",
line 12, in <module>
printme(temp,label)
TypeError: printme() takes 0 positional arguments but 2
were given
In program1, the argument types in function call and function definition are same. Also the orderof
arguments is not changed.
In program2, the number of arguments in function call is two and function definition takes nilargument
and hence throws an error.
#Program3 #Program4
#program using required arguments def printme(str):
def printme(str): print(str)
print(str) return
return printme()
temp=40
label='Its very sunny, cannot play cricket'
printme(temp,label)

Traceback (most recent call last): Traceback (most recent call last):
File "E:\Jerusalem File "E:\Jerusalem
College\Academic_Year\Jan2023- College\Academic_Year\Jan2023-
June2023\PythonProgramming\Programs\functions June2023\PythonProgramming\Programs\functions
.py", line 13, in <module> .py", line 5, in <module>
printme(temp,label) printme()
TypeError: printme() takes 1 positional argument TypeError: printme() missing 1 required positional
but 2 were given argument: 'str'
>>> >>>
j

In program3, the number of arguments in function call is two but only one argument is given in
function definition and hence throws an error.
In program4, there is no argument in function call but function definition takes one argument andhence
throws missing argument error.

2.2 Keyword Arguments


These are related to the function calls. When you use keyword arguments in a functioncall,
the caller identifies the arguments by the parameter name.
#Program 1 #Program 2
def printinfo(sport): def printinfo(team, point, sport):
print(sport) print("Team Name:",team)
return print("Points :",point)
printinfo(sport ="IPL 2023") print("Sports :", IPL2023)
return
printinfo(team="CSK",point=16, sport = "IPL 2023")
printinfo(point=13, team="RCB", sport="IPL 2023"

IPL 2023 Team Name: CSK


Points : 16
Sports : IPL2023
Team Name: RCB
Points : 13
Sports : IPL2023

Program1 takes one keyword arguments and prints its value. In program2 there are two function calls. First
printinfo(), three arguments were passed and the function definition takes the arguments in order. But in
the second printinfo(), though the order of arguments changed the final output will not be changed.
2.3 Default Arguments
This argument assumes a default value if a value is not provided in the function call forthat
argument.
#Program 1
def printinfo(sport, team='SRH'):
print("The sports name = %s & team = %s"%(sport,team))
return
printinfo(team="MI", sport="IPL 2023")
printinfo(sport="IPL 2023")

The sports name = IPL 2023 and team = MI


The sports name = IPL 2023 and team = SRH

The first printinfo( ) takes two arguments and prints the values passed namely “MI” and “IPL2023”.
Whereas, the second printinfo( ) takes only sports argument and from the function definition the second
argument value is taken and prints the answer. That is the variable team is assumed as a default argument.
j

#Program 2
def printinfo(team, point=10, sport):
print("Team Name:",team)
print("Points :",point)
print("Sports :", IPL2023)
return
printinfo(team="CSK", point=16, sport = "IPL 2023")
printinfo(point=13, team="RCB", sport="IPL 2023")

Since in program 2, the default argument is defined before the non-default argument, the above error is
thrown. The corrected program is shown below. Here the default argument is defined as alast argument.
#Corrected Program 2
def printinfo(team, sport, point=10):
print("Team Name:",team)
print("Points :",point)
print("Sports :", sport)
return
printinfo(team="CSK", point=16, sport = "IPL 2023")
printinfo(point=13, team="RCB", sport="IPL 2023")

Team Name: CSK


Points : 10
Sports : IPL 2023
Team Name: RCB
Points : 13
Sports : IPL 2023

2.4 Variable-Length Arguments


Sometimes, we may need to process a function for more arguments that is specified whiledefining
the function. These arguments are called variable-length arguments and are named in the function
definition.
j

#Program 1 #Program2
def fun(a, *args, s='!'): def fun(a, *args):
print(a,s) print(a)
for I in args: for I in args:
print(I,s) print(I)
fun(10) fun(10)
fun(10,20) fun(10,20)
fun(10,20,30) fun(10,20,30)
fun(10,20,30,40,s='+') fun(10,20,30,40')

10 ! 10
10 ! 10
20 ! 20
10 ! 10
20 ! 20
30 ! 30
10 + 10
20 + 20
30 + 30
40 + 40

In program 1, the first argument is assigned to variable a and rest of the arguments except s areassigned
to args and s value is passed is ‘+” but the default value is ‘!’.
In program 2, the first argument is assigned to variable a and rest of the arguments except s areassigned
to args.

3. SCOPE OF VARIABLES
All variables in a program may not be accessible at all locations in that program. This depends on where
you have declared a variable. The scope of a variable determines the portion of the program whereyou can access
a particular identifier. There are two basic scopes of variables in Python-

• Global variables
• Local variables

Global and Local Variable


Variables that are defined inside a function body have a local scope, and those defined outside have a global
scope. This means that local variables can be accessed only inside the function in whichthey are declared,
whereas global variables can be accessed throughout the program body by all functions. When you call a function,
the variables declared inside it are brought into scope.
j

#Global and Local variable - Program 1


print("Program 1")
def f():
s="India is our country"
print("Inside Function:", s)
# Driver code
s = "I love India"
f()
print(s)

print("Program 2")
#Global and Local variable - Program 2
total = 0
def sum( arg1, arg2 ):
total = arg1 + arg2;
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum(10,20)
print ("Outside the function global total : ", total )

#Output
Program 1
Inside Function: India is our country
I love India
Program 2
Inside the function local total : 30
Outside the function global total : 0
j

#Global and Local variable - Program 3


print("Program 3")
def f():
s="India is our country"
print("Inside Function:", s)
# Driver code
f()
print(s)
#Global and Local variable - Program 4
print("Program 4")
def f():
global s
s="India is our country"
print("Inside Function:", s)
s=s+"I Love India"
# Driver code
f()
print(s)
#Output
Program 3
Inside Function: India is our country
I love India
Program 4
Inside Function: India is our country
India is our countryI Love India

4.RECURSION AND LAMBDA FUNCTIONS


4.1 RECURSION
Definition: It is a process of calling the same/own function itself again and again untilsome
condition is satisfied.
Syntax:
def func_recursion():
……………….
……………….
func_recursion()

Some Examples for recursion:


• Factorial of number
• Fibonacci series
• Tower of Hanoi.
j

Recursive Function
#Program 1 - Countdown program
def count_down(start):
print(start) next=start-1
if next>0:
count_down(next)
else:
print("Ready Lets Go. .. ")
cnt=int(input("Enter the Count down value:"))
count_down(cnt)
#Program 2 - Factorial Finding
def fact(n):if
n==1:
print(n)return 1
else:
print(n,"*",end="")
n=n*fact(n-1)
return n

N=int(input("\nEnter the value to find factorial"))f =


fact(N)
print(N,"!=",f)
Enter the Count down value:77
6
5
4
3
2
1
Ready Lets Go....

Enter the value to find factorial66 *5 *4


*3 *2 *1
6 != 720

4.2 ANONYMOUS FUNCTION OR LAMBDA FUNCTION


These functions are not declared in the standard manner by using def keyword. We can use the
lambda keyword to create small anonymous functions.

• Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expression.
• Lambda functions have their own local namespace and cannot access variables other than those intheir
parameter list and those in the global namespace.
j

• Lambdas are a one-line version of a function.

Syntax : - lambda function contains only a single statement, which is as follows


Lambda [arg1 [,arg2,. ... argn]]:expression
j

5. DATE AND TIME METHODS

Python has a module named datetime to work with dates and times.

Example 1: Get Current Date and Time

Eg.

Example 2: Get Current Date

Eg.

2023-05-29

Commonly used classes in the datetime module are:

• date class– Manipulate just date ( Month, day, year)


• time class – Time independent of the day (Hour, minute, second, microsecond)
• datetime class – Combination of time and date (Month, day, year, hour, second,
microsecond)
• timedelta class — A duration of time used for manipulating dates

dateclass

We will use the date class of the datetime module to accomplish this task.

Example 1: Python get today's date

from datetime import date


today = date.today()
print("Today's date:", today)
Output:
Today's date: 2023-05-29
j

Here, we imported the date class from the datetime module. Then, we used the date.today() method
to get the current local date.
date.today()
By the way, returns a date object, which is assigned to the today variable in the above
program.

Now, we can use the strftime() method to create a string representing date in different formats.

• strftime() method is used for formatting.


• This method uses different control code to give an output.
• Each control code resembles different parameters like year,month, weekday and
date [(%y/%Y – Year), (%a/%A- weekday), (%b/%B- month), (%d - day of month)] .

Example 2: Current date in different formats


from datetime import date

today = date.today()

# dd/mm/YY
d1 = today.strftime("%A - %d/%m/%Y")
print("d1 =", d1)

# Textual month, day and year


d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)

# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)

# Month abbreviation, day and year


d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)

O/P:

d1 = Monday - 29/05/2023
d2 = May 29, 2023
d3 = 05/29/23
d4 = May-29-2023
j

Today's Weekday Number


The date.today() function also gives you the weekday number. Here is the Weekday Table whichstart
with Monday as 0 and Sunday as 6

Day WeekDay Number

Monday 0

Tuesday 1

Wednesday 2

Thursday 3

Friday 4

Saturday 5

Sunday 6

Eg.
from datetime import date
today=date.today()
print("Todays day is:", today.day )
print("Todays month is:", today.month )
print("Todays year is:", today.year )
print("Todays weekday is:", today.weekday())
O/P:
Todays day is: 29
Todays month is: 5
Todays year is: 2023
Todays weekday is: 0

datetimeclass

If we need to get the current date and time, we can use datetime class of the module.

from datetime import datetime

# datetime object containing current date and time


now = datetime.now()

print("now =", now) datetime

Example 3: Get the current date and time


j

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)

Output:

now = 2023-05-29 11:48:12.985487


date and time = 29/05/2023 11:48:12

✓ With the help of "Strftime" function we can also retrieve local system time, date or both.

1. %C- indicates the local date and time


2. %x- indicates the local date
3. %X- indicates the local time

Eg.
from datetime import datetime
now = datetime.now()
print(now.strftime("%c"))
print(now.strftime("%x"))
print(now.strftime("%X"))
O/P:

Mon May 29 11:48:56 2023

05/29/23

11:48:56

✓ The "strftime function" allows us to call the time in any format 24 hours or 12 hours.

Eg.
from datetime import datetime
now = datetime.now()
print(now.strftime("%I: %M:%S %p"))
#%I/%H 12-hour/24 hour, %M - Minute, %S - Second,
%p - local' AM/PM
print(now.strftime("%H:%M"))
O/P:

11: 49:56 AM

11:49
j

time class

With "DATETIME OBJECT", we can also call time class. Suppose

we want to print just the current time without the date.

t = datetime.time(datetime.now())

• We had imported the time class. We will be assigning it the current value of time using
datetime.now()
• We are assigning the value of the current time to the variable t.

And this will give just the time.

Eg.
from datetime import datetime
from datetime import time
t=datetime.time(datetime.now())
print("The current time is ",t)
O/P:
The current time is 11:51:07.712635

How to use Timedelta Objects

With timedelta objects, we can estimate the time for both future and the past. In other words, it
is a timespan to predict any special day, date or time.

Remember this function is not for printing out the time or date, but something to
CALCULATE about the future or past. Let's see an example to understand it better.

Step 1) To run Timedelta Objects, we need to declare the import statement first and then executethe
code

Eg.
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

print(timedelta(days=365, hours=12, minutes=18))


O/P:
365 days, 12:18:00

The timedelta represents a span of 365 days, 12 hrs and 18 minutes and prints the same
j

Step 2) Let's get today's date and time to check whether our import statement is working well. When code
is executed, it prints out today's date which means our import statement is working well

Eg.
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

print(timedelta(days=365, hours=12, minutes=18))

print ("today is :",str(datetime.now()))


O/P:
365 days, 12:18:00
today is : 2023-05-29 11:52:17.518660

Step 3) We can retrieve date, a year from now through delta objects.

Eg.
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
print(timedelta(days=365, hours=12, minutes=18))

print ("today is :",str(datetime.now()))

print("One year from now will be:",


datetime.now()+timedelta(days=365))
O/P:
365 days, 12:18:00
today is : 2023-05-29 11:52:53.983545
One year from now will be: 2024-05-28 11:52:53.983545

Step 4) Another example of how time delta can be used to calculate future date from current dateand
time
Eg.
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

print(timedelta(days=365, hours=12, minutes=18))

print ("today is :",str(datetime.now()))

print("One year from now will be:", datetime.now()+timedelta(days=365))

print("In 1 week and 2 days it will be:", datetime.now()+timedelta(weeks=1, days=2))


O/P:
365 days, 12:18:00
today is : 2023-05-29 11:53:30.132044
One year from now will be: 2024-05-28 11:53:30.132044
In 1 week and 2 days it will be: 2023-06-07 11:53:30.147669

Step 5) Let's look into a more complex example. Determine how many days past the New Year.

Eg.
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

today=date.today()
print("today", today)

nyd=date(today.year,1,1)
print("nyd",nyd)

if nyd<today:
print("new year is already went by %d days ago" % ((today-nyd).days))
else:
print("%d days more for new year"%((nyd-today).days))
O/P:
today 2023-05-29
nyd 2023-01-01
new year is already went by 148 days ago
Getting calendar for a month

The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here,
we print a calendar for a given month

Eg.
import calendar

cal = calendar.month(2020, 4)

print ("Here is the calendar:")

print (cal)

O/P:
Here is the calendar:

April 2020

Mo Tu We Th Fr Sa Su

1 2 3 4 5

6 7 8 9 10 11 12

13 14 15 16 17 18 19

20 21 22 23 24 25 26

27 28 29 30
6. PYTHON PACKAGES
Package in Python is a folder that contains various modules as files. The way drives, folders,
subfolders help us organize files in an OS, packages help us organize sub-packages and modules.
Purpose of package
a. Suppose you have developed a very large application that includes many modules. As the
number of modules grows, it becomes difficult to keep track of them all if they are dumped
into one location. This is particularly so if they have similar names or functionality. You might
wish for a means of grouping and organizing them.
b. Packages allow for a hierarchical structuring of the module namespace using dot notation.
Packages help avoid collisions between module names.
Built-in python packages

6.1 NumPy
NumPy is the primary tool for scientific computing in Python.
NumPy is used for:
✓ Advanced array operations (e.g. add, multiply, slice, reshape, index).
✓ Comprehensive mathematical functions.
✓ Random number generation.
✓ Linear algebra routines.
✓ Fourier transforms, etc.
6.2 Pandas
If you work with tabular, time series, or matrix data, pandas is your go-to Python package.
6.2.1 It is known as a fast, efficient, and easy-to-use tool for data analysis and
manipulation.
6.2.2 It works with data frame objects; a data frame is a dedicated structure for two-
dimensionaldata.
6.2.3 Data frames have rows and columns just like database tables or Excel
spreadsheets.Among other things, pandas can be used for:
6.2.4 Reading/writing data from/to CSV and Excel files and SQL databases.
6.2.5 Reshaping and pivoting datasets.
6.2.6 Slicing, indexing, and subsetting datasets.
6.2.7 Aggregating and transforming data.
6.2.8 Merging and joining datasets.
6.3 scikit learn
scikit-learn is an efficient and beginner-friendly tool for predictive data analysis.
Among other things, you can use scikit-learn to:
6.3.1 Identify which category an object is likely to belong to (used in fraud detection,
imagerecognition, cancer detection, etc.).
6.3.2 Predict a continuous variable based on available features (used in predicting house
pricesand inflation).
6.3.3 Group similar objects into clusters (used in customer segmentation, social network
analysis, etc.).
6.4 matplotlib
Matplotlib is the most common data exploration and visualization library.
6.4.1 You can use it to create basic graphs like line plots, histograms, scatter plots, bar
charts,and pie charts.
6.4.2 You can also create animated and interactive visualizations with this
library.The following figure plots a zig-zag line using matplotlib.
6.5 Seaborn Plots
Seaborn is a high-level interface for drawing attractive statistical graphics with just a few lines of
code.
Let us take famous IRIS FLOWER DATASET.
i. This dataset includes four features – the length and the width of the sepals and
petals – forthree species of iris (Iris setosa, Iris virginica, and Iris versicolor).
ii. Now, let us visualize how these four features relate to one another depending
on the irisspecies.
import seaborn as sns
iris = sns.load_dataset('iris')
sns.pairplot (iris, hue = 'species', palette = 'pastel')

7. How to create a package


• A particular directory is treated as a package if it contains a file named init .py in it. The directory
may contain other sub-packages and modules in it. init .py file may be empty or it may contain
some initialization code for the package.
• Suppose there is a package called pkg containing a module called mod.py. If the module contains
functions f1( ) and f2( ) then the directory structure would be as follows:
Directory - pkg
Contents of pkg directory - mod.py and init .py
Contents of mod.py - f1( ) and f2( )
Program to use f1( ) and f2( ) would be as follows:
# mod.py
def f1( ):
print('Inside function f1')
def f2( ):
print('Inside function f2')
# client.py
import pkg.mod
pkg.mod.f1()
pkg.mod.f2()

You might also like