Jcs2201-Python Programming Unit-IV Notes
Jcs2201-Python Programming Unit-IV Notes
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.
Output
Function Body
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)
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)
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.
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 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")
#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
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
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
• 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
Python has a module named datetime to work with dates and times.
Eg.
Eg.
2023-05-29
dateclass
We will use the date class of the datetime module to accomplish this task.
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.
today = date.today()
# dd/mm/YY
d1 = today.strftime("%A - %d/%m/%Y")
print("d1 =", d1)
# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)
O/P:
d1 = Monday - 29/05/2023
d2 = May 29, 2023
d3 = 05/29/23
d4 = May-29-2023
j
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.
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
Output:
✓ With the help of "Strftime" function we can also retrieve local system time, date or both.
Eg.
from datetime import datetime
now = datetime.now()
print(now.strftime("%c"))
print(now.strftime("%x"))
print(now.strftime("%X"))
O/P:
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
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.
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
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
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
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))
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
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 (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')