0% found this document useful (0 votes)
22 views16 pages

Pyth Unit IV

Uploaded by

sdpatil3742
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views16 pages

Pyth Unit IV

Uploaded by

sdpatil3742
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Modules:

Import module in Python


Python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our python code file saved
with the extension (.py) is treated as the module. We may have a runnable code inside the
python module. A module in Python provides us the flexibility to organize the code in a logical
way. To use the functionality of one module into another, we must have to import the specific
module.
Syntax:
Import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Note: In python we have help ()
Enter the name of any module, keyword, or topic to get help on writing Python programs and
using Python modules. To quit this help utility and return to the interpreter, just type "quit".
Some of the modules like os, date, and calendar so on……
>>> import sys
>>> print(sys.version)
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
>>> print(sys.version_info)
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0
>>> print(calendar.month(2021,5))
>>> print(calendar.isleap(2020))
True >>>
print(calendar.isleap(2017))
False
Python datetime module

In Python, date and time are not a data type of their own, but a module named datetime can be
imported to work with the date as well as time. Python Datetime module comes built into
Python, so there is no need to install it externally.

Python Datetime module supplies classes to work with date and time. These classes provide a
number of functions to deal with dates, times and time intervals. Date and datetime are an
object in Python, so when you manipulate them, you are actually manipulating objects and not
string or timestamps.

The DateTime module is categorized into 6 main classes –

 date – An idealized naive date, assuming the current Gregorian calendar always was,
and always will be, in effect. Its attributes are year, month and day.
 time – An idealized time, independent of any particular day, assuming that every day
has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond,
and tzinfo.
 datetime – Its a combination of date and time along with the attributes year, month,
day, hour, minute, second, microsecond, and tzinfo.
 timedelta – A duration expressing the difference between two date, time, or datetime
instances to microsecond resolution.
 tzinfo – It provides time zone information objects.
 timezone – A class that implements the tzinfo abstract base class as a fixed offset from
the UTC (New in version 3.2).

Date class

The date class is used to instantiate date objects in Python. When an object of this class is
instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs
three mandatory arguments year, month and date.

# Python program to
# demonstrate date class

# import the date class


from datetime import date

# initializing constructor
# and passing arguments in the
# format year, month, date
my_date = date(1996, 12, 11)

print("Date passed as argument is", my_date)

# Uncommenting my_date = date(1996, 12, 39)


# will raise an ValueError as it is
# outside range

# uncommenting my_date = date('1996', 12, 11)


# will raise a TypeError as a string is
# passed instead of integer

Example 2: Get Current Date

To return the current local date today () function of date class is used. today () function comes
with several attributes (year, month and day). These can be printed individually.

# Python program to
# print current date

from datetime import date

# calling the today


# function of date class
today = date.today()

print("Today's date is", today)

Output
Today's date is 2021-08-19

Example 3: Get Today’s Year, Month, and Date

We can get the year, month, and date attributes from the date object using the year, month
and date attribute of the date class.

from datetime import date

# date object of today's date


today = date.today()

print ("Current year:", today.year)


print ("Current month:", today.month)
print ("Current day:", today.day)

Output
Current year: 2021
Current month: 8
Current day: 19

Example 4: Get date from Timestamp

We can create date objects from timestamps y=using the fromtimestamp () method. The
timestamp is the number of seconds from 1st January 1970 at UTC to a particular date.

from datetime import datetime


# Getting Datetime from timestamp
date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)

List of Date class Methods


Function Name Description

ctime() Return a string representing the date

fromisocalendar() Returns a date corresponding to the ISO calendar

fromisoformat() Returns a date object from the string representation of the date

Returns a date object from the proleptic Gregorian ordinal, where January
fromordinal()
1 of year 1 has ordinal 1

fromtimestamp() Returns a date object from the POSIX timestamp

isocalendar() Returns a tuple year, week, and weekday

isoformat() Returns the string representation of the date

Returns the day of the week as integer where Monday is 1 and Sunday is
isoweekday()
7

replace() Changes the value of the date object with the given parameter

strftime() Returns a string representation of the date with the given format

timetuple() Returns an object of type time.struct_time

today() Returns the current local date

Return the proleptic Gregorian ordinal of the date, where January 1 of


toordinal()
year 1 has ordinal 1

Returns the day of the week as integer where Monday is 0 and Sunday is
weekday()
6
List of Time class Methods
Function Name Description

dst() Returns tzinfo.dst() is tzinfo is not None

fromisoformat() Returns a time object from the string representation of the time

isoformat() Returns the string representation of time from the time object

replace() Changes the value of the time object with the given parameter

strftime() Returns a string representation of the time with the given format

tzname() Returns tzinfo.tzname() is tzinfo is not None

utcoffset() Returns tzinfo.utcffsets() is tzinfo is not None

List of Datetime Class Methods


Function Name Description

astimezone() Returns the DateTime object containing timezone information.

combine() Combines the date and time objects and return a DateTime object

ctime() Returns a string representation of date and time

date() Return the Date class object

Returns a datetime object from the string representation of the date and
fromisoformat()
time

Returns a date object from the proleptic Gregorian ordinal, where


fromordinal() January 1 of year 1 has ordinal 1. The hour, minute, second, and
microsecond are 0

fromtimestamp() Return date and time from POSIX timestamp

isocalendar() Returns a tuple year, week, and weekday

isoformat() Return the string representation of date and time

Returns the day of the week as integer where Monday is 1 and Sunday
isoweekday()
is 7

now() Returns current local date and time with tz parameter


Function Name Description

replace() Changes the specific attributes of the DateTime object

Returns a string representation of the DateTime object with the given


strftime()
format

strptime() Returns a DateTime object corresponding to the date string

time() Return the Time class object

timetuple() Returns an object of type time.struct_time

timetz() Return the Time class object

today() Return local DateTime with tzinfo as None

Return the proleptic Gregorian ordinal of the date, where January 1 of


toordinal()
year 1 has ordinal 1

tzname() Returns the name of the timezone

utcfromtimestamp() Return UTC from POSIX timestamp

utcoffset() Returns the UTC offset

utcnow() Return current UTC date and time

Returns the day of the week as integer where Monday is 0 and Sunday
weekday()
is 6

Calendar Module

Python defines an inbuilt module calendar that handles operations related to the calendar.
The calendar module allows output calendars like the program and provides additional useful
functions related to the calendar. Functions and classes defined in the Calendar module use an
idealized calendar, the current Gregorian calendar extended indefinitely in both directions. By
default, these calendars have Monday as the first day of the week, and Sunday as the last (the
European convention).
Example #1: Display the Calendar of a given month.
# Python program to display calendar of
# given month of the year

# import module
import calendar

yy = 2017
mm = 11

# display the calendar


print(calendar.month(yy, mm))

Example #2: Display calendar of the given year.

# Python code to demonstrate the working of


# calendar() function to print calendar

# importing calendar module


# for calendar operations
import calendar

# using calendar to print calendar of year


# prints calendar of 2018
print ("The calendar of year 2018 is: ")
print (calendar.calendar(2018, 2, 1, 6))

The calendar class creates a Calendar object. A Calendar object provides several methods that
can be used for preparing the calendar data for formatting. This class doesn’t do any formatting
itself. This is the job of subclasses. Calendar class allows the calculations for various tasks
based on date, month, and year. Calendar class provides the following methods:

Function Description
Returns an iterator for the week day numbers that will be used for
iterweekdays()
one week
itermonthdates() Returns an iterator for the month (1–12) in the year
itermonthdays() Returns an iterator of a specified month and a year
Method is used to get an iterator for the month in the year similar to
itermonthdays2() itermonthdates(). Days returned will be tuples consisting of a day of
the month number and a week day number.
Returns an iterator for the month in the year similar to
itermonthdates(), but not restricted by the datetime.date range. Days
itermonthdays3()
returned will be tuples consisting of a year, a month and a day of the
month numbers.
Returns an iterator for the month in the year similar to
itermonthdays4()
itermonthdates(), but not restricted by the datetime.date range. Days
returned will be tuples consisting of a year, a month, a day of the
month, and a day of the week numbers.
monthdatescalendar() Used to get a list of the weeks in the month of the year as full weeks
monthdays2calendar() Used to get a list of the weeks in the month of the year as full weeks
monthdayscalendar Used to get a list of the weeks in the month of the year as full weeks
yeardatescalendar() Used to get a list of the weeks in the month of the year as full weeks
Used to get the data for specified year. Entries in the week lists are
yeardays2calendar()
tuples of day numbers and weekday numbers
Used to get the data for specified year. Entries in the week lists are
yeardayscalendar()
day numbers

Math Module

Sometimes when working with some kind of financial or scientific projects it becomes
necessary to implement mathematical calculations in the project. Python provides the math
module to deal with such calculations. Math module provides functions to deal with both basic
operations such as addition (+), subtraction (-), multiplication (*), division (/) and advance
operations like trigonometric, logarithmic, exponential functions.

Constants provided by the math module

Math module provides various the value of various constants like pi, tau. Having such constants
saves the time of writing the value of each constant every time we want to use it and that too
with great precision. Constants provided by the math module are –

 Euler’s Number
 Pi
 Tau
 Infinity
 Not a Number (NaN)

Euler’s Number

The math.e constant returns the Euler’s number: 2.71828182846.

Syntax:

math.e
# Import math Library

import math

# Print the value of Euler e

print (math.e)

Pi

You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. math.pi provides a
more precise value for the pi.

Syntax:

math.pi

# Import math Library

import math

# Print the value of pi

print (math.pi)

Tau

Tau is defined as the ratio of the circumference to the radius of a circle. The math.tau
constant returns the value tau: 6.283185307179586.

Syntax:

math.tau

# Import math Library

import math

# Print the value of tau

print (math.tau)
Infinity

Infinity basically means something which is never-ending or boundless from both directions
i.e. negative and positive. It cannot be depicted by a number. The math.inf constant returns
of positive infinity. For negative infinity, use -math.inf.

Syntax:

math.inf

# Import math Library

import math

# Print the positive infinity

print (math.inf)

# Print the negative infinity

print (-math.inf)

NaN

The math.nan constant returns a floating-point nan (Not a Number) value. This value is not a
legal number. The nan constant is equivalent to float(“nan”).

# Import math Library

import math

# Print the value of nan

print (math.nan)
List of Mathematical function in Python

Function Name Description


ceil(x) Returns the smallest integral value greater than the number
copysign(x, y) Returns the number with the value of ‘x’ but with the sign of ‘y’
fabs(x) Returns the absolute value of the number
factorial(x) Returns the factorial of the number
floor(x) Returns the greatest integral value smaller than the number
gcd(x, y) Compute the greatest common divisor of 2 numbers
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
fsum(iterable) Returns the precise floating-point value of sum of elements in an iterable
isfinite(x) Check whether the value is neither infinity not Nan
isinf(x) Check whether the value is infinity or not
isnan(x) Returns true if the number is “nan” else returns false
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns the value of e raised to the power x(e**x)
expm1(x) Returns the value of e raised to the power a (x-1)
log(x[, b]) Returns the logarithmic value of a with base b
log1p(x) Returns the natural logarithmic value of 1+x
log2(x) Computes value of log a with base 2
log10(x) Computes value of log a with base 10
pow(x, y) Compute value of x raised to the power y (x**y)
sqrt(x) Returns the square root of the number
acos(x) Returns the arc cosine of value passed as argument
asin(x) Returns the arc sine of value passed as argument
atan(x) Returns the arc tangent of value passed as argument
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of value passed as argument
hypot(x, y) Returns the hypotenuse of the values passed in arguments
sin(x) Returns the sine of value passed as argument
tan(x) Returns the tangent of the value passed as argument
degrees(x) Convert argument value from radians to degrees
radians(x) Convert argument value from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of value passed as argument
asinh(x) Returns the inverse hyperbolic sine of value passed as argument
atanh(x) Returns the inverse hyperbolic tangent of value passed as argument
Function Name Description
cosh(x) Returns the hyperbolic cosine of value passed as argument
sinh(x) Returns the hyperbolic sine of value passed as argument
tanh(x) Returns the hyperbolic tangent of value passed as argument
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Return the gamma function of the argument
lgamma(x) Return the natural log of the absolute value of the gamma function

Python File

Files are identified locations on the disc where associated data is stored. They are used to retain
data in non-volatile memory indefinitely (e.g. hard disk). Because Random Access Memory
(RAM) is volatile (it loses data when the computer is shut off), we employ files to store data
for future use by permanently storing it.

When we wish to read or write to a file, we must first open it. When we’re finished, it needs to
be closed so that the resources associated with the file may be released. As a result, Python file
operations occur in the following order:

 Opening a file
 Reading or writing a file (perform operation)
 Closing the file

In Python, there are two sorts of files that can be handled: text files and binary files (written in
binary language- 0s and 1s)

 Binary files – The majority of files you use on a regular basis on your computer are
binary files, not text ones. That’s right, even though it only contains text, the Microsoft
Word.doc file is a binary file. There is no line terminator in this form of a file, and the
data is kept after it has been converted into machine-readable binary language.
 Text files – A text file, on the other hand, does not require any special encoding and
may be opened with any ordinary text editor. Each line of text in this sort of file is
terminated with a special character known as EOL (End of Line), which is the new line
character (‘\n’) in Python by default.

Opening Files in Python

To open a file, Python includes the open () function. This function returns a file object, often
known as a handle, which is used to read or change the file. This function does not require the
import of any modules.

File_object = open(filename, access_mode)

where,
 filename – name of the file that the file object has to open
 access_mode – attribute of the file that tells which mode a file was opened in. Default
is reading in text mode

 >>> f = open('myFile.txt') # opens file in current directory

 >>> f = open('C:\MyFolder\myFile.txt') # specifying full path

Mode Description
r Allows you to open a file for reading. (default)

This command opens a file for writing. If the file does not exist, it is
w
created; otherwise, it is truncated.

Opens a file for the purpose of exclusive creation. The operation


x
fails if the file already exists.

Opens a file for adding at the end without truncating it. If the file
a
does not exist, it is created.

t Opens a file in text mode (default)

b Opens in binary mode.

+ Opens a file for modification (reading and writing)

Writing to Files in Python

Files are useless if you can’t write data to them. To accomplish this, we can employ the Python
write () function. This adds the characters you specify to the end of a file. Keep in mind that
when you create a new file object, Python will create the file if it does not already exist. When
making your first file, you should utilize either the a+ or w+ modes. We must exercise caution
when using the w mode, as it will overwrite the file if it already exists. As a result, all previous
data is deleted.

There are two ways to enter data into a file:

1. Python write() –

Inserts the string str1 into the text file on a single line.

File_object.write(str1)

2. Python writelines() –
Each string is inserted into the text file for a list of string elements. Used to insert many
strings at once.

File_object.writelines(L) for L = [str1, str2, str3]

Example

with open('Recipe.txt', 'w') as file:


file.write('5 eggs\n')
file.write('2 tsp baking powder\n')
file.write('60g butter\n')
file.write('2 cup sugar\n')

Output

5 eggs
2 tsp baking powder
60g butter
2 cup sugar

Reading Files in Python

To begin reading a file in Python, open the file you wish to read. Python requires you to specify
the name and location of the file you want to open. To read a file in Python, we must first open
it in reading r mode. To read data from a file, we can use one of three functions, which are as
follows:

1. Python read() –

The fileobject.read(size) method is used to read the contents of a file. If no size option
is specified, this method will read the full file and send it to the console as a string (in
text mode) or as byte objects (in binary mode). The size parameter instructs the read
method how many bytes to return to the display from the file.

File_object.read([n])

>>> f = open('Recipe.txt','r',encoding = 'utf-8')


>>> f.read(10) # reads the first 10 data
'5 eggs\n2 t'

>>> f.read(20) # reads the next 20 data


'sp baking powder\n60g'

>>> f.read() # reads the rest of the data till the end of file
' butter\n2 cup sugar\n2 cup water\n250ml skimmed milk\n'
2. Python readline() –

Data in a file can also be parsed by reading it line by line. This allows you to scan an
entire file line by line, progressing only when necessary. Reads a line from a file and
returns it as a string. Reads at most n bytes for the provided n. However, even if n is
greater than the length of the line, does not read more than one line.

File_object.readline([n])

>>> f = open('Recipe.txt','r',encoding = 'utf-8')


>>> f.readline()
'5 eggs\n'

>>> f.readline()
'2 tsp baking powder\n'

>>> f.readline()
'60g butter\n'

>>> f.readline()
'2 cup sugar\n'

3. Python readlines() –

The fileobject.readlines() method (note the plural), which produces a list of all the lines
in the file. This method reads all the lines and returns them as string elements in a list,
one for each line.

File_object.readlines()

>>> f = open('Recipe.txt','r',encoding = 'utf-8')


>>> f.readlines()
['5 eggs\n', '2 tsp baking powder\n', '60g butter\n', '2 cup sugar\n', '2 cup water\n',
'250ml skimmed milk\n']
Python File Methods

To conduct various Python file operations with the help of file objects, you may use a variety
of methods. Some of them were utilized in the above examples. Let us look at some more
Python file operation methods below:

Method Description
This function closes an open file. If the file is already closed, it
close()
has no effect.
Returns the underlying binary buffer after separating it from the
detach()
TextIOBase.
fileno() The file’s integer number (file descriptor) is returned.
flush() Flushes the file stream’s write buffer.
isatty() If the file stream is interactive, this method returns True.
Reads a maximum of n characters from the file. If it is negative
read(n)
or None, it reads till the end of the file.
readable() If the file stream can be read from, this method returns True.
Reads one line from the file and returns it. If n is supplied, it
readline(n=-1)
reads in at most n bytes.
Reads the file and returns a list of lines. If n bytes/characters are
readlines(n=-1)
given, this function reads in at most n bytes/characters.
Changes the file position in reference to from to offset bytes
seek(offset,from=SEEK_SET)
(start, current, end).
If the file stream enables random access, this function returns
seekable()
True.
tell() The current file location is returned.
The file stream is resized to size bytes. If no size is supplied, it
truncate(size=None)
resizes to the current position.
writable() If the file stream can be written to, this method returns True.
Returns the number of characters written after writing the string
write(s)
s to the file.
writelines(lines) A list of lines is written to the file.

You might also like