0% found this document useful (0 votes)
2 views41 pages

Python Programming Unit-IV

Python programming

Uploaded by

Somen Debnath
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)
2 views41 pages

Python Programming Unit-IV

Python programming

Uploaded by

Somen Debnath
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/ 41

UNIT – IV

FILES, EXCEPTIONS
File I/O, Exception Handling, introduction to basic standard libraries, Installation of pip,
Demonstrate Modules: Turtle, pandas, numpy, pdb, Explore packages.

Files and exception:

A file is some information or data which stays in the computer storage devices. Python
gives you easy ways to manipulate these files. Generally, files divide in two categories,
text file and binary file. Text files are simple text whereas the binary files contain binary
data which is only readable by computer.

• Text files: In this type of file, each line of text is terminated with a special
character called EOL (End of Line), which is the new line character („\n‟) in
python by default.
• Binary files: In this type of file, there is no terminator for a line and the data is
stored after converting it into machine understandable binary language.

An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.

Text files:

We can create the text files by using the syntax:

Variable name=open (“file.txt”, file mode)

For ex: f= open ("hello.txt","w+")

• We declared the variable f to open a file named hello.txt. Open takes 2 arguments,
the file that we want to open and a string that represents the kinds of permission
or operation we want to do on the file
• Here we used "w" letter in our argument, which indicates write and the plus sign
that means it will create a file if it does not exist in library
• The available option beside "w" are "r" for read and "a" for append and plus sign
means if it is not there then create it
File Modes in Python:

Mode Description
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing.
If file does not exist, it creates a new file. If file exists it
truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)

Reading and Writing files:

The following image shows how to create and open a text file in notepad from command
prompt

(or)

Hit on enter then it shows the following whether to open or not?


Click on “yes” to open else “no” to cancel

# Write a python program to open and read a file

a=open(“one.txt”,”r”)
print(a.read())
a.close()

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/filess/f1.py
welcome to python programming
(or)

Note: All the program files and text files need to saved together in a particular file
then only the program performs the operations in the given file mode

f.close() ---- This will close the instance of the file somefile.txt stored
# Write a python program to open and write “hello world” into a file?
f=open("1.txt","a")
f.write("hello world")
f.close()

Output:

(or)

Note: In the above program the 1.txt file is created automatically and adds hello
world into txt file

If we keep on executing the same program for more than one time then it append the data
that many times

# Write a python program to write the content “hi python programming” for the
existing file.

f=open("1.txt",'w')
f.write("hi python programming")
f.close()

Output:

In the above program the hello txt file consists of data like
But when we try to write some data on to the same file it overwrites and saves with
the
current data (check output)

# Write a python program to open and write the content to file and read it.

fo=open("abc.txt","w+")
fo.write("Python Programming")
print(fo.read())
fo.close()

Output:

(or)

Note: It creates the abc.txt file automatically and writes the data into it

Command line arguments:

The command line arguments must be given whenever we want to give the input
before the start of the script, while on the other hand, raw_input() is used to get the
input while the python program / script is running.

5
The command line arguments in python can be processed by using either „sys‟
module,
„argparse‟ module and „getopt‟ module.

“sys” module:

Python sys module stores the command line arguments into a list, we can access
it using sys.argv. This is very useful and simple way to read command line arguments
as String.
sys.argv is the list of commandline arguments passed to the Python program. argv
represents all the items that come along via the command line input, it's basically an
array holding the command line arguments of our program

>>> sys.modules.keys() -- this prints so many dict elements in the form of list.

# Python code to demonstrate the use of 'sys' module for command line
arguments

import sys

# command line arguments are stored in the form


# of list in sys.argv

argumentList = sys.argv
print(argumentList)

# Print the name of file


print(sys.argv[0])

# Print the first argument after the name of file


#print(sys.argv[1])
Output:
C:/Users/DoCSE-LP1/Desktop/abc.py
['C:/Users/DoCSE-LP1/Desktop/abc.py']
C:/Users/DoCSE-LP1/Desktop/abc.py

Note: Since my list consist of only one element at „0‟ index so it prints only that list
element, if we try to access at index position „1‟ then it shows the error like,

IndexError: list index out of range

import sys

6
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Output:
C:/Users/DoCSE-LP1/Desktop/abc.py
<class 'list'>
The command line arguments are:
C:/Users/DoCSE-LP1/Desktop/abc.py
# Write a python program to get python version.
import sys

print("System version is:")


print(sys.version)
print("Version Information is:")
print(sys.version_info)

Output:
C:/Users/DoCSE-LP1/Desktop/abc.py
System version is:
3.12.3 (tags/v3.12.3:f6650f9, Apr 9 2024, 14:05:25) [MSC v.1938 64 bit (AMD64)]
Version Information is:
sys.version_info(major=3, minor=12, micro=3, releaselevel='final', serial=0)

“getopt” module:
Python getopt module is very similar in working as the C getopt() function for
parsing command-line parameters. Python getopt mod u l e is useful in parsing
command line arguments where we want user to enter some options too.

import argparse
parser = argparse.ArgumentParser()
print(parser.parse_args())

“argparse” module :
Python argparse module is the preferred way to parse command line arguments. It
provides a lot of option such as positional arguments, default value for arguments,
help message, specifying data type of argument etc

It parses the command line options and parameter list. The signature of this function
is mentioned below:

getopt.getopt(args, shortopts, longopts=[ ])

7
• args are the arguments to be passed.
• shortopts is the options this script accepts.
• Optional parameter, longopts is the list of String parameters this function
accepts which should be supported. Note that the -- should not be prepended
with option names.

-h---------print help and usage message


-m-------accept custom option value
-d--------run the script in debug mode

import getopt
import sys

argv = sys.argv[0:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
Output:
C:/Users/DoCSE-LP1/Desktop/error.py
['C:/Users/DoCSE-LP1/Desktop/error.py']

Errors and Exceptions:


Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors. When writing a program, we, more o f t e n t h a n n o t , w i l l
encounter errors. Error caused by not following the proper structure (syntax) of the
language is called syntax error or parsing error

ZeroDivisionError:
ZeroDivisionError in Python indicates that the second argument used in a division (or
modulo) operation was zero.

OverflowError:
OverflowError in Python indicates that an arithmetic operation has exceeded the
limits of the current Python runtime. This is typically due to excessively large float
values, as integer values that are too big will opt to raise memory errors instead.

ImportError:

8
It is raised when you try to import a module which does not exist. This may happen
if you made a typing mistake in the module name or the module doesn't exist in its
standard path. In the example below, a module named "non_existing_module" is
being imported but it doesn't exist, hence an import error exception is raised.
IndexError:
An IndexError exception is raised when you refer a sequence which is out of range.
In the example below, the list abc contains only 3 entries, but the 4th index is being
accessed, which will result an IndexError exception.

TypeError:
When two unrelated type of objects are combined, TypeErrorexception is raised.In
example below, an int and a string is added, which will result in TypeError exception.

IndentationError:
Unexpected indent. As mentioned in the "expected an indented block" section, Python
not only insists on indentation, it insists on consistent indentation. You are free to
choose the number of spaces of indentation to use, but you then need to stick with it.

Syntax errors:
These are the most basic type of error. They arise when the Python parser is unable
to understand a line of code. Syntax errors are almost always fatal, i.e. there is almost
never a way to successfully execute a piece of code containing syntax errors.

Run-time error:
A run-time error happens when Python understands what you are saying, but runs into
trouble when following your instructions.

Key Error:

Python raises a KeyError whenever a dict() object is requested (using the format a
= adict[key]) and the key is not in the dictionary.

Value Error:
In Python, a value is the information that is stored within a certain object. To
encounter a ValueError in Python means that is a problem with the content of the
object you tried to assign the value to.

Python has many built-in exceptions which forces your program to output an error
when something in it goes wrong. In Python, users can define such exceptions by
creating a new class. This exception class has to be derived, either directly
or indirectly, from Exception class.

Different types of exceptions:

9
• ArrayIndexOutOfBoundException.
• ClassNotFoundException.
• FileNotFoundException.
• IOException.
• InterruptedException.
• NoSuchFieldException.
• NoSuchMethodException

Handling Exceptions:

The cause of an exception is often external to the program itself. For example, an
incorrect input, a malfunctioning IO device etc. Because the program abruptly
terminates on encountering an exception, it may cause damage to system resources,
such as files. Hence, the exceptions should be properly handled so that an abrupt
termination of the program is prevented.

Python uses try and except keywords to handle exceptions. Both keywords are
followed by indented blocks.

Syntax:
try :
#statements in try block
except :
#executed when error in try block

Typically we see, most of the times


• Syntactical errors (wrong spelling, colon ( : ) missing ….),
At developer level and compile level it gives errors.

• Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,),
As a developer we test the application, during that time logical error may
obtained.

• Run time error (In this case, if the user doesn‟t know to give input, 5/6 is ok
but if the user say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by
zero)) This is not easy compared to the above two errors because it is not done
by the system, it is (mistake) done by the user.

The things we need to observe are:


1. You should be able to understand the mistakes; the error might be done by user,
DB connection or server.
2. Whenever there is an error execution should not stop. Ex: Banking Transaction

10
3. The aim is execution should not stop even though an error occurs.

For ex:

a=5
b=2
print(a/b)
print("Bye")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex1.py
2.5
Bye
• The above is normal execution with no error, but if we say when b=0, it is
a critical and gives error, see below

a=5
b=0
print(a/b)
print("bye") #this has to be printed, but abnormal termination

Output:
Traceback (most recent call last):

File "C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex2.py", line 3,


in
<module>
print(a/b)

ZeroDivisionError: division by zero

• To overcome this we handle exceptions using except keyword

a=5
b=0
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex3.py

11
number can not be divided by zero
bye

• The except block executes only when try block has an error, check it below

a=5
b=2
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex4.py
2.5

For example if you want to print the message like what is an error in a program then
we use “e” which is the representation or object of an exception.

a=5
b=0
try:
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("bye")
Output:

C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex5.py
number can not be divided by zero division by zero
bye

(Type of error)

Let us see some more examples:


I don‟t want to print bye but I want to close the file whenever it is opened. a=5
b=2
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:

12
print("number can not be divided by zero",e)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex6.py

resource opened 2.5


resource closed

Note: the file is opened and closed well, but see by changing the value of b to 0,

a=5
b=0
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex7.py
resource opened
number can not be divided by zero division by zero

Note: resource not closed


• To overcome this, keep print(“resource closed”) in except block, see it

a=5
b=0
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex8.py
resource opened
number can not be divided by zero division by zero
resource closed

The result is fine that the file is opened and closed, but again change the value of b to

13
back (i.e., value 2 or other than zero)
a=5
b=2
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex9.py
resource opened
2.5

• But again the same problem file/resource is not closed


• To overcome this python has a feature called finally:

This block gets executed though we get an error or not

Note: Except block executes, only when try block has an error, but finally block
executes, even though you get an exception.

a=5
b=0

try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
finally:
print("resource closed")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
the value can not be divided by zero division by zero
resource closed

change the value of b to 2 for above program, you see the output like

14
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number 6
6
resource closed

Instead give input as some character or string for above program, check the
output
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open 2.5
enter a number p
resource closed

Traceback (most recent call last):


File "C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py", line
7, in <module>

#----------------------------
a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
except ValueError as e:
print("invalid input")
except Exception as e:
print("something went wrong...",e)
finally:
print("resource closed")
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex11.py
resource open
the value cannot be divided by zero division by zero
resource closed

Change the value of b to 2 and give the input as some character or string (other
than int)
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ex12.py

15
resource open
2.5
enter a number p
invalid input
resource closed

Introduction to basic standard libraries


Modules (Date, Time, os, calendar, math):
• Modules refer to a file containing Python statements and definitions.
• We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.
• Modular programming refers to the process of breaking a large, unwieldy
programming task into separate, smaller, more manageable subtasks or
modules.

Advantages :
• Simplicity: Rather than focusing on the entire problem at hand, a module
typically focuses on one relatively small portion of the problem. If you‟re
working on a single module, you‟ll have a smaller problem domain to wrap
your head around. This makes development easier and less error-prone.
• Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains. If modules are written in a way
that minimizes interdependency, there is decreased likelihood that
modifications to a single module will have an impact on other parts of the
program. This makes it more viable for a team of many programmers to work
collaboratively on a large application.
• Reusability: Functionality defined in a single module can be easily reused
(through an appropriately defined interface) by other parts of the application.
This eliminates the need to recreate duplicate code.
• Scoping: Modules typically define a separate namespace, which helps avoid
collisions between identifiers in different areas of a program.
• Functions, modules and packages are all constructs in Python that promote
code modularization.

A file containing Python code, for e.g.: example.py, is called a module and its module
name would be example.

>>> def add(a,b):


result=a+b
return result

16
"""This program adds two numbers and return the result""“

Here, we have defined a function add() inside a module named example. The function
takes in two numbers and returns their sum.

How to import the module is:


• We can import the definitions inside a module to another module or the
Interactive interpreter in Python.
• We use the import keyword to do this. To import our previously defined
module example we type the following in the Python prompt.
• Using the module name we can access the function using dot (.) operation. For
Eg:

>>> import example


>>> example.add(5,5)

10

• Python has a ton of standard modules available. Standard modules can be


imported the same way as we import our user-defined modules.

Reloading a module:

def hi(a,b):
print(a+b)
hi(4,4)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/add.py
8
>>> import add
8
>>> import add
>>> import add
>>>
Python provides a neat way of doing this. We can use the reload() function

17
inside the imp module to reload a module. This is how its done.
>>> import imp
>>> import my_module
• This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed <module 'my_module' from '.\\my_module.py'>how its done.

>>> import imp


>>> import add
>>> imp.reload(add)
8
<module 'add' from 'C:/Users//AppData/Local/Programs/Python/Python38-
32/pyyy\\add.py'>

The dir() built-in function

>>> import example

>>> dir(example)

[' builtins ', ' cached ', ' doc ', ' file ', ' loader ',
' name ', ' package ', ' spec ', 'add']

>>> dir()

[' annotations ', ' builtins ', ' doc ', ' file ', '
loader ', ' name ',

' package ', ' spec ', ' warningregistry ', 'add', 'example', 'hi', 'imp']

It shows all built-in and user-defined modules.

For ex:
>>> example. name

'example'

Datetime module:

# Write a python program to display date, time

18
>>> import datetime

>>> a=datetime.datetime(2019,5,27,6,35,40)

>>> a

datetime.datetime(2019, 5, 27, 6, 35, 40)

# write a python program to display date


import datetime a=datetime.date(2000,9,18)
print(a)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2000-09-18

# write a python program to display time

import datetime
a=datetime.time(5,3)
print(a)
Output:

C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =

05:03:00

#write a python program to print date, time for today and now.

a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29 12:49:52.235581
2019-11-29 12:49:52.235581

#write a python program to add some days to your present date and print the
date added.

import datetime a=datetime.date.today()

19
b=datetime.timedelta(days=7)
print(a+b)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-12-06

#write a python program to print the no. of days to write to reach your birthday
import datetime
a=datetime.date.today()
b=datetime.date(2020,5,27)
c=b-a
print(c)

Output
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
180 days, 0:00:00

#write an python program to print date, time using date and time functions

import datetime
t=datetime.datetime.today()
print(t.date())
print(t.time())

Output:

C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29
12:53:39.226763

Time module:

#write a python program to display time.

import time print(time.time())


Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =

1575012547.1584706

#write a python program to get structure of time stamp.

import time

20
print(time.localtime(time.time()))

time.struct_time(tm_year=2019, tm_mon=11, tm_mday=29, tm_hour=13, tm_min=1,


tm_sec=15, tm_wday=4, tm_yday=333, tm_isdst=0)

#write a python program to make a time stamp. import time


a=(1999,5,27,7,20,15,1,27,0)
print(time.mktime(a))Output
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
927769815.0

#write a python program using sleep().


import time
time.sleep(6) #prints after 6 seconds
print("Python Lab")
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
Python Lab (#prints after 6 seconds)

os module:
>>> import os
>>> os.name 'nt'
>>> os.getcwd()
'C:\\Users\\ \\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'

>>> os.mkdir("temp1")

Note: temp1 dir is created

>>> os.getcwd()

'C:\\Users\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'

>>> open("t1.py","a")

21
<_io.TextIOWrapper name='t1.py' mode='a' encoding='cp1252'>
>>> os.access("t1.py",os.F_OK)
True
>>> os.access("t1.py",os.W_OK)
True
>>> os.rename("t1.py","t3.py")
>>> os.access("t1.py",os.F_OK)
False
>>> os.access("t3.py",os.F_OK)
True
>>> os.rmdir('temp1') (or)
os.rmdir('C:/Users/ /AppData/Local/Programs/Python/Python38-32/pyyy/temp1')

Note: Temp1dir is removed

>>> os.remove("t3.py")

Note: We can check with the following cmd whether removed or not

>>> os.access("t3.py",os.F_OK)
False
>>> os.listdir()

['add.py', 'ali.py', 'alia.py', 'arr.py', 'arr2.py', 'arr3.py', 'arr4.py', 'arr5.py', 'arr6.py',


'br.py',
'br2.py', 'bubb.py', 'bubb2.py', 'bubb3.py', 'bubb4.py', 'bubbdesc.py', 'clo.py',
'cmndlinarg.py',
'comm.py', 'con1.py', 'cont.py', 'cont2.py', 'd1.py', 'dic.py', 'e1.py', 'example.py',
'f1.y.py',
'flowof.py', 'fr.py', 'fr2.py', 'fr3.py', 'fu.py', 'fu1.py', 'if1.py', 'if2.py', 'ifelif.py',
'ifelse.py',
'iff.py', 'insertdesc.py', 'inserti.py', 'k1.py', 'l1.py', 'l2.py', 'link1.py', 'linklisttt.py',
'lis.py',
'listlooop.py', 'm1.py', 'merg.py', 'nesforr.py', 'nestedif.py', 'opprec.py',
'paraarg.py',

22
'qucksort.py', 'qukdesc.py', 'quu.py', 'r.py', 'rec.py', 'ret.py', 'rn.py', 's1.py',
'scoglo.py',
'selecasce.py', 'selectdecs.py', 'stk.py', 'strmodl.py', 'strr.py', 'strr1.py', 'strr2.py',
'strr3.py',
'strr4.py', 'strrmodl.py', 'wh.py', 'wh1.py', 'wh2.py', 'wh3.py',
'wh4.py', 'wh5.py', ' che ']
>>> os.listdir('C:/Users/ /AppData/Local/Programs/Python/Python38-
32')['argpar.py', 'br.py', 'bu.py', 'cmndlinarg.py', 'DLLs', 'Doc', 'f1.py',
'f1.txt', 'filess',
'functupretval.py', 'funturet.py', 'gtopt.py', 'include', 'Lib', 'libs', 'LICENSE.txt',
'lisparam.py',
'mysite', 'NEWS.txt', 'niru', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe',
'pyyy',
'Scripts', 'srp.py', 'sy.py', 'symod.py', 'tcl', 'the_weather', 'Tools',
'tupretval.py',

'vcruntime140.dll']
Calendar module:

#write a python program to display a particular month of a year using calendar


module.
import calendar
print(calendar.month(2020,1))
Output:

# write a python program to check whether the given year is leap or not.

import calendar print(calendar.isleap(2021))


Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/cl1.py
False
#write a python program to print all the months of given year.
import calendar print(calendar.calendar(2020,1,1,1))

Output:

23
math module:
# write a python program which accepts the radius of a circle from user and
computes the area.
import math r=int(input("Enter radius:")) area=math.pi*r*r
print("Area of circle is:",area)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/m.py =
Enter radius:4

24
Area of circle is: 50.26548245743669

>>> import math

>>> print("The value of pi is", math.pi)


O/P: The value of pi is 3.141592653589793 Import with renaming:
We can import a module by renaming it as follows.
For Eg:

>>> import math as m

>>> print("The value of pi is", m.pi)

O/P: The value of pi is 3.141592653589793

We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope.
Hence, math.pi is invalid, m.pi is the correct implementation.
Python from...import statement:

We can import specific names from a module without importing the module as a
whole. Here is an example.

>>> from math import pi


>>> print("The value of pi is", pi)

O/P: The value of pi is 3.141592653589793

We imported only the attribute pi from the module.


In such case we don't use the dot operator. We could have imported multiple attributes
as follows.
>>> from math import pi, e
>>> pi 3.141592653589793
>>> e 2.718281828459045

Import all names:


We can import all names(definitions) from a module using the following construct.
>>>from math import *
>>>print("The value of pi is", pi)
We imported all the definitions from the math module. This makes all names except
those beginnig with an underscore, visible in our scope.

Explore packages:

25
We don't usually store all of our files in our computer in the same location. We use a
well-organized hierarchy of directories for easier access.
Similar files are kept in the same directory, for example, we may keep all the songs
in the "music" directory. Analogous to this, Python has packages for directories
and modules for files.

As our application program grows larger in size with a lot of modules, we place
similar modules in one package and different modules in different packages. This
makes a project (program) easy to manage and conceptually clear.
Similar, as a directory can contain sub-directories and files, a Python package can
have sub-packages and modules.

A directory must contain a file named init .py in order for Python to consider it
as a package. This file can be left empty but we generally place the initialization code
for that package in this file.
Here is an example. Suppose we are developing a game, one possible organization of
packages and modules could be as shown in the figure below.

If a file named init .py is present in a package directory, it is invoked when the package
or a module in the package is imported. This can be used for execution of package

26
initialization code, such as initialization of package-level data.
For example init .py

A module in the package can access the global by importing it in turn

We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as
follows.

import Game.Level.start

Now if this module contains a function named select_difficulty(), we must use the
full name to reference it.

Game.Level.start.select_difficulty(2)

If this construct seems lengthy, we can import the module without the package prefix
as follows.

from Game.Level import start


We can now call the function simply as follows.

start.select_difficulty(2)

Yet another way of importing just the required function (or class or variable) form a
module within a package would be as follows.

from Game.Level.start import select_difficulty


Now we can directly call this function.
select_difficulty(2)
Examples:

#Write a python program to createa package (II


YEAR), sub-package (CSE), modules(student) and create read and write
function to module

def read(): print("Department")


def write(): print("Student")
Output:
>>> from IIYEAR.CSE import student

>>> st udent.read() Department


>>> student.write() Student

27
>>> from IIYEAR.CSE.student import read
>>> read

<function read at 0x03BD1070>

>>> read() Department


>>> from IIYEAR.CSE.student import write

>>> write()

Student
# Write a program to create and import module?
def add(a=4,b=6):
c=a+b
return c

Output:

C:\Users\ \AppData\Local\Programs\Python\Python38-32\IIYEAR\modu1.py>>>
from IIYEAR import modu1
>>> modu1.add() 10
# Write a program to create and rename the existing module.

def a():

print("hello world")

a()
Output:

C:/Users//AppData/Local/Programs/Python/Python38-32/IIYEAR/exam.py hello
world
>>> import exam as ex
hello world

Installation of pip:
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.

Package: A package contains all the files you need for a module. Modules are Python
code libraries you can include in your project.
Check if PIP is Installed

28
Navigate your command line to the location of Python's script directory, and type the
following:

Example

Check PIP version:

C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip --
version
Install PIP

If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/

Download a Package

Downloading a package is very easy.

Open the command line interface and tell PIP to download the package you want.

Navigate your command line to the location of Python's script directory, and type the
following:

Example

Download a package named "camelcase":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip
install camelcase
Now you have downloaded and installed your first package!

Using a Package:-

Once the package is installed, it is ready to use. Import the "camelcase" package into
your project.
Example
Import and use "camelcase":
import camelcase

c = camelcase.CamelCase() txt = "hello world" print(c.hump(txt))

Find Packages:-
Find more packages at https://pypi.org/.

29
Remove a Package

Use the uninstall command to remove a package:

Example Uninstall the package named "camelcase":


C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip
uninstall camelcase

The PIP Package Manager will ask you to confirm that you want to remove the
camelcase package:

Uninstalling camelcase-02.1:
Would remove:
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-
packages\camecase- 0.2-py3.6.egg-info
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-
packages\camecase\* Proceed (y/n)?

Press y and the package will be removed.

Turtle: Turtle is a special feathers of Python. Using Turtle, we can easily draw in a
drawing board. First we import the turtle module. Then create a window, next we
create turtle object and using turtle method we can draw in the drawing board.
Some turtle method

METHOD PARAMETER DESCRIPTION

Turtle() None It creates and returns a new turtle object

forward() amount It moves the turtle forward by the specified amount

backward() amount It moves the turtle backward by the specified amount

right() angle It turns the turtle clockwise

left() angle It turns the turtle counter clockwise

30
penup() None It picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

heading() None It returns the current heading

position() None It returns the current position

goto() x, y It moves the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None It closes the polygon and fills with the current fill color

dot() None Leaves the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current


location
shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Example code
# import turtle library import turtle

31
my_window = turtle.Screen()
my_window.bgcolor("blue") # creates a graphics window
my_pen = turtle.Turtle()
my_pen.forward(150)
my_pen.left(90)
my_pen.forward(75)
my_pen.color("white")
my_pen.pensize(12)

Output

Draw a Square Example code

# import turtle library import turtle


my_pen = turtle.Turtle() for i in range(4):
my_pen.forward(50) my_pen.right(90)
turtle.done()

Output

Draw a star Example code

# import turtle library import turtle

32
my_pen = turtle.Turtle()
for i in range(50):
my_pen.forward(50)
my_pen.right(144)
turtle.done()

Output

Draw a Hexagon Example code

# import turtle library import turtle


polygon = turtle.Turtle()
my_num_sides = 6
my_side_length = 70
my_angle = 360.0 / my_num_sides
for i in range(my_num_sides):
polygon.forward(my_side_length)
polygon.right(my_angle)
turtle.done()

Output

Pandas : Pandas is an open-source library that is made mainly for working with
relational or labeled data both easily and intuitively. It provides various data structures
and operations for manipulating numerical data and time series. This library is built
on the top of the NumPy library. Pandas is fast and it has high-performance &
productivity for users.
• Fast and efficient for manipulating and analyzing data.
• Data from different file objects can be loaded.
• Easy handling of missing data (represented as NaN) in floating point as well as
non-floating point data
• Size mutability: columns can be inserted and deleted from DataFrame and
higher dimensional objects

33
• Data set merging and joining.
• Flexible reshaping and pivoting of data sets
• Provides time-series functionality.
• Powerful group by functionality for performing split-apply-combine operations
on data sets.

Getting Started: After the pandas has been installed into the system, you need to
import the library. This module is generally imported as –

import pandas as pd
Here, pd is referred to as an alias to the Pandas. However, it is not necessary to import
the library using alias, it just helps in writing less amount of code everytime a method
or property is called.

Pandas generally provide two data structure for manipulating data, They are:
Series
DataFrame
Series

Pandas Series is a one-dimensional labeled array capable of holding data of any type
(integer, string, float, python objects, etc.). The axis labels are collectively called
index. Pandas Series is nothing but a column in an excel sheet. Labels need not be
unique but must be a hashable type. The object supports both integer and label-based
indexing and provides a host of methods for performing operations involving the

index.

Creating a Series

34
In the real world, a Pandas Series will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, and Excel file. Pandas Series can be
created from the lists, dictionary, and from a scalar value etc.

import pandas as pd import numpy as np

# Creating empty series


ser = pd.Series()

print(ser)

# simple array
data = np.array(['g', 'e', 'e', 'k', 's'])

ser = pd.Series(data)
print(ser)

Output:
Series([], dtype: float64)
0 g
1 e
2 e
3 k
4 s
dtype: object

DataFrame

35
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous
tabular data structure with labeled axes (rows and columns). A Data frame is a two-
dimensional data structure, i.e., data is aligned in a tabular fashion in rows and
columns. Pandas DataFrame consists of three principal components, the data, rows,
and columns.
Creating a DataFrame :In the real world, a Pandas DataFrame will be created by
loading the datasets from existing storage, storage can be SQL Database, CSV
file, and Excel file. Pandas DataFrame can be created from the lists, dictionary, and
from a list of dictionary etc.

Example:

import pandas as pd

# Calling DataFrame constructor df = pd.DataFrame()


print(df)

# list of strings
lst = ['aaa', 'bbb', 'ccc']

# Calling DataFrame constructor on list df = pd.DataFrame(lst)


print(df)

Output:
Empty DataFrame Columns: [] Index: []
0
aaa
bbb
ccc

Python Numpy
Numpy is a general-purpose array-processing package. It provides a high-
performance multidimensional array object, and tools for working with these arrays.
It is the fundamental package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-
dimensional container of generic data.

Arrays in Numpy

Array in Numpy is a table of elements (usually numbers), all of the same type, indexed
by a tuple of positive integers. In Numpy, number of dimensions of the array is called
rank of the array.A tuple of integers giving the size of the array along each dimension
is known as shape of the array. An array class in Numpy is called as ndarray. Elements

36
in Numpy arrays are accessed by using square brackets and can be initialized by using
nested Python Lists.

Creating a Numpy Array


Arrays in Numpy can be created by multiple ways, with various number of Ranks,
defining the size of the Array. Arrays can also be created with the use of various data
types such as lists, tuples, etc. The type of the resultant array is deduced from the type
of the elements in the sequences.
Note: The type of array can be explicitly defined while creating the array. # Python
program for
# Creation of Arrays
import numpy as np

# Creating a rank 1 Array


arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)

# Creating a rank 2 Array


arr = np.array([[1, 2, 3],
[4, 5, 6]])
print("Array with Rank 2: \n", arr)

# Creating an array from tuple


arr = np.array((1, 3, 2))
print("\nArray created using "
"passed tuple:\n", arr)
Output:
Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]

Array created using passed tuple:


[1 3 2]

Accessing the array Index


In a numpy array, indexing or accessing the array index can be done in multiple ways.
To print a range of an array, slicing is done. Slicing of an array is defining a range in
a new array which is used to print a range of elements from the original array. Since,
sliced array holds a range of elements of the original array, modifying content with
the help of sliced array modifies the original array content.

37
# Python program to demonstrate # indexing in numpy array import numpy as np

# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ") print(arr)

# Printing a range of Array


# with the use of slicing method

sliced_arr = arr[:2, ::2]


print ("Array with first 2 rows and"
" alternate columns(0 and 2):\n", sliced_arr)

# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), (1, 2), (0, 1), (3, 0):
\n", Index_arr)

Output:
Initial Array:
[[-1. 2. 0. 4. ]
[ 4. -0.5 6. 0. ]
[ 2.6 0. 7. 8. ]
[ 3. -7. 4. 2. ]]
Array with first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[ 0. 54. 2. 3.]

Array Operations: In numpy, arrays allow a wide range of operations which can be
performed on a particular array or a combination of Arrays. These operation include
some basic Mathematical operation as well as Unary and Binary operations.

# Python program to demonstrate # basic operations on single array import numpy as


np

38
# Defining Array 1
a = np.array([[1, 2],
[3, 4]])

# Defining Array 2
b = np.array([[4, 3],
[2, 1]])

# Adding 1 to every element


print ("Adding 1 to every element:", a + 1)

# Subtracting 2 from each element


print ("\nSubtracting 2 from each element:", b - 2)
# sum of array elements
# Performing Unary operations
print ("\nSum of all array "
"elements: ", a.sum())

# Adding two arrays


# Performing Binary operations print ("\nArray sum:\n", a + b)

Output:
Adding 1 to every element: [[2 3]
[4 5]]

Subtracting 2 from each element: [[ 2 1]


[ 0 -1]]

Sum of all array elements: 10

Array sum: [[5 5]


[5 5]]

Pdb:

In software development jargon, 'debugging' term is popularly used to process of


locating and rectifying errors in a program. Python's standard library contains pdb
module which is a set of utilities for debugging of Python programs.
The debugging functionality is defined in a Pdb class. The module internally makes
used of bdb and cmd modules.
The pdb module has a very convenient command line interface. It is imported at the
time of execution of Python script by using –m switch

39
python –m pdb script.py
In order to find more about how the debugger works, let us first write a Python module
(fact.py) as
follows −

def fact(x): f = 1
for i in range(1,x+1):
print (i)
f=f*i
return f
if name ==" main ":
print ("factorial of 3=",fact(3))
Start debugging this module from command line. In this case the execution halts at
first line in the code by showing arrow (->) to its left, and producing debugger prompt
(Pdb)

C:\python36>python -m pdb fact.py


c:\python36\fact.py(1)<module>()
-> def fact(x):
(Pdb)
To see list of all debugger commands type 'help' in front of the debugger prompt. To
know more about any command use 'help <command>' syntax.

The list command lists entire code with -> symbol to the left of a line at which program

40
has halted.

(Pdb) list
1 -> def fact(x):
2 f=1
for i in range(1,x+1):
print (i)
f=f*i
return f
if name ==" main ":
print ("factorial of 3 = ", fact(3))

To move through the program line by line use step or next command.

(Pdb) step
c:\python36\fact.py(7)<module>()
-> if name ==" main ": (Pdb) next
c:\python36\fact.py(8)<module>()
-> print ("factorial of 3 = ", fact(3))
(Pdb) next 1
2
3
factorial of 3= 6
--Return--
c:\python36\fact.py(8)<module>()->None
-> print ("factorial of 3 = ", fact(3))

41

You might also like