python1
python1
MODULE - I
Agenda:
Python Basics,
Getting started,
Python Objects,
Numbers,
Sequences:
Strings,
Lists,
Tuples,
Set and Dictionary.
Conditionals and Loop Structures
Python is a simple programming language. When we read Python program, we can feel like
Reading English statements. The syntaxes are very simple and only 30+ keywords are
available. When compared with other languages, we can write programs with very less
number of lines. Hence more readability and simplicity.
We can use Python software without any licence and it is freeware.Its source code is
open,so that we can we can customize based on our requirement.
Eg: Jython is customized version of Python to work with Java Applications.
Platform Independent:
Once we write a Python program, it can run on any platform without rewriting once again.
Internally PVM is responsible to convert into machine understandable form.
Portability:
Python programs are portable. ie we can migrate from one platform to another platform
very easily. Python programs will provide same results on any paltform.
Dynamically Typed:
In Python we are not required to declare type for variables. Whenever we are assigning the
value, based on value, type will be allocated automatically.Hence Python is considered as
dynamically typed language.But Java, C etc are Statically Typed Languages because we
have to provide type at the beginning only.
Extensible:
We can use other language programs in Python,The main advantages of this approach are:
1. We can use already existing legacy non-Python code
2. We can improve performance of the application
Embedded:
We can use Python programs in any other language programs. i.e we can embedd Python
programs anywhere.
Extensive Library:
Python has a rich inbuilt library.Being a programmer we can use this library directly and we
are not responsible to implement the functionality.
Versions of Python:
Python Applications:
The following are different area we can use python programming language
In Python 2 the following 2 functions are available to read dynamic input from the
keyboard.
1. raw_input()
2. input()
1. raw_input():
This function always reads the data from the keyboard in the form of String Format. We
have to convert that string type to our required type by using the corresponding type casting
methods.
Eg:
2. input():
input() function can be used to read data directly in our required format.We are not required
to perform type casting.
Eg:
x=input("Enter a Value)
type(x)
20 ===> int
"DS"===>str
125.5===>float
True==>bool
In Python 3 we have only input() method and raw_input() method is not available.
Python3 input() function behaviour exactly same as raw_input() method of Python2.
i.e every input value is treated as str type only.
Example:
x=input("Enter First Number:")
y=input("Enter Second Number:")
a = int(x)
b = int(y)
print("Sum=",a+b)
output:
Enter First Number:10
Enter Second Number:20
Sum=30
OutPut Function:
We use the print() function or print keyword to output data to the standard output device
(screen). This function prints the object/string written in function
Examples:
print("Hello World")
We can use escape characters also
print("Hello \n World")
print("Hello\tWorld")
We can use repetetion operator (*) in the string
print(10*"Hello")
Reserved Words
In Python some words are reserved to represent some meaning or functionality. Such
type of words are called Reserved words.
We cannot use a keyword as a variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly over the course
of time.
All the keywords except True, False and None are in lowercase and they must be
written as they are. The list of all the keywords is given below.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif If or yield
1. Decimal form(base-10):
It is the default number system in Python
The allowed digits are: 0 to 9
Eg: a =10
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg: a = 0B1111
a =0B123
a=b111
3. Octal Form(Base-8):
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O
Eg: a=0o123
a=0o786
Example:
>>> a=10
>>> b=0B0101
>>> c=0o121
>>> d=0xabc
>>> print(a)
10
>>> print(b)
5
>>> print(c)
81
>>> print(d)
2748
Base Conversions
Python provide the following in-built functions for base conversions
1.bin():
We can use bin() to convert from any base to binary
Eg:
>>> bin(5)
'0b101'
>>> bin(0o11)
'0b1001'
>>> bin(0X10)
'0b10000'
2. oct():
We can use oct() to convert from any base to octal
Eg:
>>> oct(10)
'0o12'
>>> oct(0B1111)
'0o17'
>>> f=0o123.456
SyntaxError: invalid syntax
>>> f=0X123.456
SyntaxError: invalid syntax
5. str type:
str represents String data type.
A String is a sequence of characters enclosed within single quotes or double quotes.
s1='MREC'
s1="MREC"
By using single quotes or double quotes we cannot represent multi line string literals.
s1="MREC DS"
For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
s1='''MREC
DS'''
s1="""MREC
DS"""
We can also use triple quotes to use single quote or double quote in our String.
>>> s1='''"This is mrec"'''
>>> s1
'"This is mrec"'
We can embed one string in another string
>>> s1='''This "Python Programming Session" for DS Students'''
>>> s1
'This "Python Programming Session" for DS Students'
Slicing of Strings:
slice means a piece
[ ] operator is called slice operator,which can be used to retrieve parts of String.
In Python Strings follows zero based index.
The index can be either +ve or -ve.
+ve index means forward direction from Left to Right
-ve index means backward direction from Right to Left
Eg:
-7 -6 -5 -4 -3 -2 -1
>>> s[1:4]
'REC'
>>> s[0:4]
'MREC'
>>> s[0:]
'MREC DS'
>>> s[:4]
'MREC'
>>> s[:]
'MREC DS'
>>> len(s)
7
Type Casting in Python
We can convert one type value to another type. This conversion is called Typecasting or
Type conversion.
The following are various inbuilt functions for type casting.
1. int()
2. float()
2. float():
We can use float() function to convert other type values to float type.
We can convert any type value to float type except complex type.
Whenever we are trying to convert str type to float type compulsary str should be
either integral or floating point literal and should be specified only in base-10.
Eg:
1) >>> float(26)
2) 26.0
3) >>> float(True)
4) 1.0
5) >>> float(False)
6) 0.0
7) >>> float("26")
8) 26.0
3.complex():
We can use complex() function to convert other types to complex type.
We can use this function to convert x into complex number with real part x and
imaginary
We can use this method to convert x and y into complex number such that x will be
real part and y will be imaginary part.
Eg:
1) complex(26)
26+0j
2) complex(26.26)
26.26+0j
3) complex(True)
1+0j
4) complex(False)
0j
5) complex("26")
26+0j
6) complex("26.26")
26.26+0j
7) complex("MREC")
ValueError: complex() arg is a malformed string
8)complex(26,26)
26+26j
9)complex(True,False)
1+0j
4. bool():
We can use this function to convert other type values to bool type.
Eg:
1) bool(0)
An operator is a symbol that tells the compiler to perform certain mathematical or logical
Manipulations. Operators are used in program to manipulate data and variables.
Python language supports the following types of operators.
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
1. Arithmetic Operators:
Arithmetic operators are used with numeric values to perform common mathematical
operations:
/ operator always performs floating point arithmetic. Hence it will always
returns float value.
Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If at least one argument is float
type then result is float type.
Assume variable „x‟ holds 5 and variable „y‟ holds 2, then:
Operator Name Example
+ Addition - Adds values on either side of the operator x + y=7
Subtraction - Subtracts right hand operand from left hand
- x – y=3
operand
Multiplication - Multiplies values on either side of the
* x * y=10
operator
Division - Divides left hand operand by right hand
/ x / y=2.5
operand
Modulus - Divides left hand operand by right hand
% x % y=1
operand and returns remainder
Exponent - Performs exponential (power) calculation on
** x ** y=25
operators
Floor Division - The division of operands where the result
// is the quotient in which the digits after the decimal point x // y=2
are removed.
Eg:
>>> x=5
>>> y=2
>>> print('x+y=',x+y)
x+y= 7
3. Logical operators:
Logical operators are used to combine conditional statements:
X Y X AND Y X OR Y NOT X
False False False False True
False True False True True
Ture False False True False
True True True True False
Eg:
>>> x=5
>>> y=2
>>> x and y
2
>>> print(x>=5 and y<=5)
True
>>> print(x>=5 or y<=5)
True
>>> print(not x>=5)
False
4. Bitwise operators:
Bitwise operator works on bits and performs bit by bit operation.
We can apply these operators bitwise on int and boolean types.
By mistake if we are trying to apply for any other type then we will get Error.
Eg:
>>> x=5
>>> y=2
>>> print('x & y=',x&y)
x & y= 0
>>> print('x | y=',x|y)
x | y= 7
>>> print('X ^ y=',x^y)
X ^ y= 7
>>> print('~x=',~x)
~x= -6
>>> print('x>>1=',x>>1)
x>>1= 2
>>> print('y<<1=',y<<1)
y<<1= 4
6.Assignment operators:
Assignment operators are used to assign values to variables:
5. Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
Operator is: It returns true if two variables point the same object and false
otherwise
Operator is not: It returns false if two variables point the same object and true
otherwise2 identity operators are available.
Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Eg:
>>> x=5
>>> y=5
>>> print(x is y)
True
>>> print(id(x))
2265011481008
>>> print(id(y))
2265011481008
>>> print(x is not y)
False
2. Membership Operators
These operators test for membership in a sequence such as lists, strings or
tuples. There are two membership operators that are used in Python. (in, not
in). It gives the result based on the variable present in specified sequence or
string
For example here we check whether the value of x=4 and value of y=8 is
available in list or not, by using in and not in operators.
Operator Description Example
in Returns True if a sequence with the specified value is x in y
present in the object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
Example:
>>> exp=10+20*30
>>> print(exp)
610
Example:
>>> exp=100/10*10
>>> print(exp)
100.0
Please see the following precedence and associativity table for reference. This table
lists all operators from the highest precedence to the lowest precedence.
Operator Description Associativity
() Parentheses left-to-right
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
is, is not Identity left-to-right
in, not in Membership operators
Conditional statement
Conditional statements will decide the execution of a block of code based on the
expression.
The conditional statements return either True or False.
A Program is just a series of instructions to the computer, But the real strength of
Programming isn‟t just executing one instruction after another. Based on how the
expressions evaluate, the program can decide to skip instructions, repeat them, or
choose one of several instructions to run. In fact, you almost never want your
programs to start from the first line of code and simply execute every line, straight to
the end. Flow control statements can decide which Python instructions to execute
under which conditions.
Python supports four types of conditional statements,
1) Simple if or if statement
if condition : statement
or
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed
Example:
>>> a=10
>>> b=5
>>> if(a>b):
print("a is big")
a is big
>>> if a>b:
print("a is big")
a is big
2) if else:
if condition :
Statements-1
else :
Statements-2
if condition is true then Statements-1 will be executed otherwise Statements-2 will be
executed.
Example:
>>> a=10
>>> b=25
>>> if(a>b):
print("a is big")
else:
print("b is big")
Syntax:
if condition1:
Statements-1
elif condition2:
Statements -2
elif condition3:
Statements -3
elif condition4:
Statements -4
...
else:
Default Action
Based condition the corresponding action will be executed.
Example:
>>> Option=int(input("Enter a value b/w(1-5)"))
Enter a value b/w(1-5)2
>>> if(Option==1):
print("you entered one")
elif(Option==2):
print("You entered Two")
elif(Option==3):
print("You entered Three")
elif(Option==4):
print("You entered Four")
elif(Option==5):
print("You entered Five")
else:
print("Enter Value b/w (1-5) only")
4. nested if statement
We can use if statements inside if statements, this is called nested if statements.
Synatx:
Login successful:
Iterative Statements
If we want to execute a group of statements multiple times then we should go for Iterative
statements.
Python supports 2 types of iterative statements.
1. for loop
2. while loop
1) for loop:
If we want to execute some action for every element present in some sequence(it may be
string or collection)then we should go for for loop.
Syntax:
for x in sequence :
body
Where sequence can be string or any collection.
Body will be executed for every element present in the sequence.
Eg 1: To print characters present in the given string
>>> s="MREC"
>>> for r in s:
print(r)
M
1
2
3
4
5
2) while loop:
If we want to execute a group of statements iteratively until some condition false,then we
should go for while loop.
Syntax:
while condition :
body
1) break:
We can use break statement inside loops to break loop execution based on some
condition.
Eg:
for r in (1,2,3,4,5):
if(r==3):
print("Break the loop")
break
print(r)
OutPut:
1
2
Break the loop
2) continue:
We can use continue statement to skip current iteration and continue next iteration.
Eg 1: To print even numbers in the range 1 to 10
for r in (1,2,3,4,5,6,7,8,9,10):
if(r%2!=0):
continue
print(r)
OutPut:
2
4
6
8
10
4. r=range(0,5)
r[0]==>0
r[15]==>IndexError: range object index out of range
We cannot modify the values of range data type
7.list data type:
If we want to represent a group of values as a single entity where insertion order
required to preserve and duplicates are allowed then we should go for list data type.
An ordered, mutable, heterogeneous collection of elements is nothing but list, where
Duplicates also allowed.
insertion order is preserved
heterogeneous objects are allowed
duplicates are allowed
Growable in nature
values should be enclosed within square brackets.
1. Eg:
Eg:
>>> d={1:"one",2:"Two",3:"Three"}
>>> d[1]
'one'
>>> d
{1: 'one', 2: 'Two', 3: 'Three'}
>>> d[4]="Four"
>>> d
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}
>>> d[5]="error"
>>> d
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'error'}
>>> d[5]="Five"
>>> d
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five'}
11. None Datatype:
The None Datatype is used to define the null value or no value, the none value
means not 0, or False value, and it is a data it's own
None keyword is an object and is a data type of nonetype class
None datatype doesn‟t contain any value.
None keyword is used to define a null variable or object.
None keyword is immutable.
Eg:
Assume a=10, that means a is the reference variable pointing to 10 and if I take a=none
then a is not looking to the object 10
>>> a=10
>>> type(a)
<class 'int'>
>>> a=None
>>> type(a)
<class 'NoneType'>
MODULE - II
Agenda:
Like many other programming languages, Python supports modularity. That is, you
can break large code into smaller and more manageable pieces. And through
modularity, Python supports code reuse.
We can import modules in Python into your programs and reuse the code therein as
many times as you want.
Modules provide us with a way to share reusable functions.
2.Eg:
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist',
'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma',
'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod',
'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
output:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
calendar.month_name:
An array that represents the months of the year in the current locale. This follows normal
convention of January being month number 1, so it has a length of 13 and month_name[0]
is the empty string.
>>> import calendar
>>> for i in calendar.month_name:
print(i)
January
February
March
April
May
June
July
August
September
October
November
December
calendar.monthrange(year, month): Returns weekday of first day of the month and
number of days in month, for the specified year and month.
>>> import calendar
>>> print(calendar.monthrange(2021,6))
Creating a Module:
Shown below is a Python script containing the definition of sum() function. It is
saved as calc.py.
#calc.py
def sum(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def di(x, y):
return x / y
Importing a Module
We can now import this module and execute the any functions which are there in calac.py
module in the Python shell.
>>> import calc
>>> print(calc.sum(4,5))
9
>>> print(calc.sub(4,5))
-1
>>> print(calc.mul(4,5))
20
Global Namespace
The Variable which can be read from anywhere in the program is known as a global scope.
These variables can be accessed inside and outside the function. When we want to use the
same variable in the rest of the program, we declare it as global.
Eg:
n=0#global namesapce
def f1():
n=1#local namespace
print("local variable n=",n)
f1()
print("Global variable n=",n)
OutPut:
local variable n= 1
Global variable n= 0
Built-in Scope
If a Variable is not defined in local,or global scope, then python looks for it in the
built-in scope.
In the Following Example, 1 from math module pi is imported, and the value of pi
is not defined in global, local and enclosed.
Python then looks for the pi value in the built-in scope and prints the value. Hence
the name which is already present in the built-in scope should not be used as an
identifier.
Eg: f1()
# Built-in Scope f2()
from math import pi print('pi is Built-in
# pi = 'Not defined in scope',pi)
global pi' OutPut:
def f1(): Not defined in f1() pi
print('Not defined in f1() Not defined in f2() pi
pi') pi is Built-in scope
def f2(): 3.141592653589793
print('Not defined in f2()
pi')
Example: Suppose we are developing a game. One possible organization of packages and
modules could be as shown in the figure below.
Eg 1:
F:\>
|-test.py
|-python_package
|-First.py
|-Second.py
|-__init__.py
test.py
--------------
from python_package import First,second
First.f1()
second.f2()
First.py
---------
def f1():
print("This is First function")
OutPut:
This is First function
This is Second Function
Python File Handling Before we move into the topic ―Python File Handling‖, let us
try to understand why we need files?
So far, we have been receiving the input data from the console and writing the output
data back to the console.
The console only displays a limited amount of data. Hence we don‘t have any issues
if the input or output is small. What if the output or input is too large?
We use files when we have large data as input or output.
A file is nothing but a named location on disk which stores data.
Files are also used to store data permanently since it stores data on non-volatile
memory.
Most modern file systems are composed of three main parts:
1. Header: metadata about the contents of the file (file name, size, type, and
so on)
2. Data: contents of the file as written by the creator or editor
3. End of file (EOF): special character that indicates the end of the file
Open a file
Read or write a file
Close a file
Opening a File:
Before performing any operations like read or write on a file, the first thing we need
to do is open a file.
Python provides an in-built function open() to open a file.
The open function accepts two parameters: the name of the file and the access mode.
The access mode specifies what operation we are going to perform on a file whether
it is read or write.
The open() function in turn returns a file object/handle, with which we can perform
file operations based on the access mode.
Syntax: file_object=open(filename, access_mode)
The allowed modes in Python are
r : open an existing file for read operation. The file pointer is positioned at the
beginning of the file. If the specified file does not exist then we will get
FileNotFoundError. This is default mode.
w : open an existing file for write operation. If the file already contains some data
then it will be overridden. If the specified file is not already available then this mode
will create that file.
a : open an existing file for append operation. It won't override existing data. If the
specified file is not already available then this mode will create a new file.
r+ : To read and write data into the file. The previous data in the file will not be
deleted. The file pointer is placed at the beginning of the file.
a+ : To append and read data from the file.It wont override existing data.
x : To open a file in exclusive creation mode for write operation. If the file already
exists then we will get FileExistsError.
All the above modes are applicable for text files. If the above modes suffixed with
'b' then these represents for binary files.
rb,wb,ab,r+b,w+b,a+b,xb
Closing a File:
After completing our operations on the file,it is highly recommended to close the file. For
this we have to use close() function. f.close()
Writing data to text files:
We can write character data to the text files by using the following 2 methods.
write(str)
writelines(list of lines)
Eg:1
1) f=open("abcd.txt",'w')
2) f.write("MREC \n")
3) f.write("CSE \n")
4) f.write("DS\n")
5)f.write("Dept\")
6) f.close()
abcd.txt:
MREC
CSE
DS
DEPT
Eg 2:
1) f=open("abcd.txt",'a')
2) list=["\nAI&ML\n","IOT\n","RAJ"]
3) f.writelines(list)
4) f.close()
abcd.txt:
MREC
CSE
DS
DEPT
AI&ML
IOT
RAJ
Reading Character Data from text files:
We can read character data from text file by using the following read methods.
read() To read total data from the file
read(n) To read 'n' characters from the file
readline()To read only one line
readlines() To read all lines into a list
Output
MREC
CSE
DS
DEPT
AI&ML
IOT
RAJ
Output
MREC
CSE
DS
Eg 4: To read all lines into list:
f=open("abc.txt",'r')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close()
output: 0
MR
2
EC
MREC
Eg:
>>>
f=open("C:/Users/rajas/AppData/Local/Programs/Python/Python39/m2.py",'r')
>>> f.name
'C:/Users/rajas/AppData/Local/Programs/Python/Python39/m2.py'
>>> f.mode
'r'
>>> f.closed
False
Python has the following set of methods available for the file object.
Method Description
close() Closes the file
fileno() Returns a number that represents the stream, from the operating system's perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
f = open("raj.txt", "r")
print(f.read())
f.close()
f = open("raj.txt", "r")
print(f.fileno())
f = open("myfile.txt", "a")
f.write("Now the file has one more line!")
f.flush()
f.write("...and another one!")
The isatty() method returns True if the file stream is interactive, example: connected
to a terminal device.
f = open("raj.txt", "r")
print(f.isatty())
The read() method returns the specified number of bytes from the file. Default is -1
which means the whole file.
f = open("raj.txt", "r")
print(f.read())
The readable() method returns True if the file is readable, False if not.
f = open("raj.txt", "r")
print(f.readable())
f = open("raj.txt", "r")
print(f.readlines())
f = open("raj.txt", "r")
print(f.readline())
f = open("raj.txt", "r")
f.seek(4)
print(f.readline())
f = open("raj.txt", "r")
print(f.seekable())
f = open("raj.txt", "r")
print(f.tell())
f = open("demofile2.txt", "a")
f.truncate(20)
f.close()
f = open("raj.txt", "a")
print(f.writable())
f = open("demofile2.txt", "a")
f.write("See you soon!")
f.close()
f = open("raj.txt", "a")
f.writelines(["See you soon!", "Over and out."])
f.close()
Open a file
Read or write a file
Close a file
f1=open('mrec.jpg','rb')
f2=open('mrec1.jpg','wb')
#bytes=f1.read()
f2.write(f1.read())
print("Image copied from f1 to f2:\n")
f1.close()
f2.close()
OutPut:
The cwd= C:\Users\rajas\AppData\Local\Programs\Python\Python39
Syntax: os.rename(old_name,new_name)
import os
os.rename('Raj','mrec')
print("The Directory Raj Renamed to mrec")
OutPut:
The Directory Raj Renamed to mrec
Here is an example:
>>> import os
To remove a directory:
To remove or delete a directory path in Python, rmdir( ) is used which is defined in
os module.
rmdir( ) works only when the directory we want to delete is empty, else it raises an
OS error.
So here are the ways to remove or delete empty and non-empty directory paths.
>> import os
>>> os.chdir('F:/Raj')
>>> os.mkdir('cse')
>>> os.listdir()
['cse']
>>> os.rmdir('cse')
>>> import os
>>> os.chdir('F:/')
>>> os.listdir()
['$RECYCLE.BIN', 'abcd.txt', 'add.txt', 'Applicant Details-Cloud.doc', 'c.py',
'cal.csv', 'exp2.py', 'filedemo.c', 'filedemo.exe', 'filedemo.o', 'first.py', 'first.txt',
'Raj']
>>> os.path.isfile('add.txt')
True
>>> os.path.isdir('Raj')
True
There are two aspects to preserving data for long-term use: converting the data back
and forth between the object in-memory and the storage format, and working with
the storage of the converted data.
The standard library includes a variety of modules that handle both aspects in
different situations.
Serialization:
Serialization in Python is a mechanism of translating data structures or object state into
a format that can be stored or transmitted and reconstructed later.
De-serialization:
The reverse operation of serialization is called de-serialization
The type of manual conversion, of an object to string or byte format (and vice versa)
is very cumbersome and tedious. It is possible to store the state of a Python object in
the form of byte stream directly to a file, or memory stream and retrieve to its
original state. This process is called serialization and de-serialization.
Python‘s built in library contains various modules for serialization and de-
serialization process. They are as follows.
Name of the
S.No. Description
Module
1 pickle Python specific serialization library
2 marshal Library used internally for serialization
3 shelve Pythonic object persistence
4 csv library for storage and retrieval of Python data to CSV format
5 json Library for serialization to universal JSON format
The problem with above program is the binary file requires bytes object only for that
we have convert to bytes object only.
To provide solution for this we have use any above modules
Pickle Module
Pickling is the process whereby a python object is converted into byte stream.
Unpickling is the reverse of this whereby a byte stream is converted back into an
object.
We can implement pickling and unpickling by using pickle module of Python.
pickle module contains dump() function to perform pickling.
Syntax:pickle.dump(object,file)
pickle module contains load() function to perform unpickling
Syntax:obj=pickle.load(file)
Eg:
import pickle
dict={1:"cse",2:"ds"}
f=open('bin.bin','wb')
pickle.dump(dict,f)
f.close()
f=open('bin.bin','rb')
s=pickle.load(f)
print(s)
f.close()
OutPut:
{1: 'cse', 2: 'ds'}
marshal Module
The marshal module is used to serialize data—that is, convert data to and from
character strings, so that they can be stored on file.
marshal.load(file) :
This function reads one value from the open readable binary file and returns it. EOF Error,
ValueError or TypeError is raised if no value is read.
Example:
import marshal
dict={1:"cse",2:"ds"}
f=open('bin.bin','wb')
marshal.dump(dict,f)
f.close()
f=open('bin.bin','rb')
s=marshal.load(f)
print(s)
f.close()
OutPut:
{1: 'cse', 2: 'ds'}
Command-line Arguments
There are many different ways in which a program can accept inputs from the user.
The common way in Python Command-line Arguments is the input() method.
Another way to pass input to the program is Command-line arguments. Almost
every modern programming language support command line arguments.
In a similar fashion, python does support command line arguments. It‘s a very
important feature as it allows for dynamic inputs from the user.
In a command-line argument, the input is given to the program through command
prompt rather than python script like input() method.
The Argument which are passing at the time of execution are called Command Line
Arguments.
Python supports different modules to handle command-line arguments. one of the
popular one of them is sys module.
import sys
print(type(sys.argv))
Output:
D:\>py c.py
<class 'list'>
Example2:
from sys import argv
print('The Number of Command Line Arguments:', len(argv))
print('The List of Command Line Arguments:', argv)
print('Command Line Arguments one by one:')
Runtime errors:
Runtime errors are also called exceptions.
When the program is executing, if something goes wrong because of end user input
or, programming logic or memory problems etc then we will call them runtime
errors.
Exception:
An exception is nothing but an unwanted or unexpected block which disturbs the normal
execution flow of program.
An Exception is a run time error that happens during the execution of program.
An exception is an error that happens during the execution of a program.
Python raises an exception whenever it tries to execute invalid code.
Error handling is generally resolved by saving the state of execution at the moment
the error occurred and interrupting the normal flow of the program to execute a
special function or piece of code, which is known as the exception handler.
Depending on the kind of error ("division by zero", "file open error" and so on)
which had occurred, the error handler can "fix" the problem and the program can be
continued afterwards with the previously saved data.
Eg:
1. print(2/0) ==>ZeroDivisionError: division by zero
2. print(2/"ten") ==>TypeError: unsupported operand type(s) for /: 'int' and 'str'
a=int(input("Enter Number:"))
print(a)
D:\>py test.py
2
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten‘
1. ZeroDivisionError:
2. NameError:
>>> print("a=",a)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print("a=",a)
NameError: name 'a' is not defined
3. IndexError:
>>> name="MREC"
>>> print(name[10])
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print(name[10])
IndexError: string index out of range
4. ValueError:
>>> a=int(input("Enter a value:"))
Enter a value:Raj
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
a=int(input("Enter a value:"))
ValueError: invalid literal for int() with base 10: 'Raj'
5. TypeError:
>>> a=10
>>> b="raj"
>>> print(a/b)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print(a/b)
TypeError: unsupported operand type(s) for /: 'int' and 'str'
7. FileNotFoundError:
>>> f=open('Raj.txt','r')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
f=open('Raj.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'Raj.txt'
8. ModuleNotFoundError:
>>> import cse_ds
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
import cse_ds
ModuleNotFoundError: No module named 'cse_ds'
Every exception in Python is an object. For every exception type the corresponding
classes are available.
Whenever an exception occurs PVM will create the corresponding exception object
and will check for handling code.
If handling code is not available then Python interpreter terminates the program
abnormally and prints corresponding exception information to the console.
The rest of the program won't be executed. This entire process we call it as Default
Exception Handling
If an exception raised inside any method then the method is responsible to create
Exception object with the following information.
Name of the exception.
Description of the exception.
The code which may raise exception is called risky code and we have to take risky
code inside try block. The corresponding handling code we have to take inside except
block.
We can handle the Exception with following ways.
Syntax:
try :
#statements in try block
except :
#executed when error in try block
Example: Without Specific error type:
print("Start:")
print("Exception Handling without Specific Error Type:")
try:
print(15/0)
except:
print("Start:")
try:
x=int(input("Enter First Number: "))
3.Raise an Exception
An exception can be raised forcefully by using the raise clause in Python. It is useful
in in that scenario where we need to raise an exception to stop the execution of the
program.
Syntax : raise Exception_class,<value>
To raise an exception, the raise statement is used. The exception class name follows
it.An exception can be provided with a value that can be given in the parenthesis.
To access the value "as" keyword is used. "e" is used as a reference variable which
stores the value of the exception.
We can pass the value to an exception to specify the exception type
Example 1:
print("Start:")
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
print("Stop")
OutPut:6
Start:
Enter a number upto 100: 200
Some time we have to define and raise exceptions explicitly to indicate that
something goes wrong, such type of exceptions are called User Defined Exceptions
or Customized Exceptions.
Programmer is responsible to define these exceptions and Python not having any
idea about these. Hence we have to raise explicitly based on our requirement by
using "raise" Keyword.
steps to create user defined exceptions
class YourException(Exception):
def __init__(self, message):
self.message = message
__init__ :
"__init__" is a reseved method in python classes. It is known as a constructor in
object oriented concepts. This method called when an object is created from the
class and it allow the class to initialize the attributes of a class.
Step 2: Raising Exception
Now you can write a try-except block to catch the user-defined exception in
Python.
For testing, inside the try block we are raising exception using raise keyword.
raise YourException("Userdefined Exceptions")
It creates the instance of the exception class YourException. You can pass any
message to your exception class instance.
Step 3: Catching Exception
Now you have to catch the user-defined exception using except block.
except YourException as err:
print(err.message)
We are catching user defined exception called YourException.
class ChildrenException(Exception):
def __init__(self,arg):
self.msg=arg
class YouthException(Exception):
def __init__(self,arg):
self.msg=arg
class AdultException(Exception):
def __init__(self,arg):
self.msg=arg
class SeniorException(Exception):
def __init__(self,arg):
self.msg=arg
age=int(input("Enter Age:"))
if (age<18) and (age>0):
raise ChildrenException("The Person having the age between (0-18)!!!")
elif (age<25) and (age>=19):
raise YouthException("The Person having the age between (19-24)!!!")
try:
marks=int(input("Enter the marks of a subject:"))
if(marks<35) and (marks>=0):
raise FailException("Fail")
elif(marks>=35):
raise PassException("Pass")
else:
raise MarksException("Marks should be positive")
except FailException as e:
print(e)
except PassException as e:
print(e)
except MarksException as e:
Python assert keyword is defined as a debugging tool that tests a condition. The
Assertions are mainly the assumption that asserts or state a fact confidently in
the program.
The process of identifying and fixing the bug is called debugging.
Very common way of debugging is to use print() statement. But the problem with
the print() statement is after fixing the bug,compulsory we have to delete the
extra added print() statments,otherwise these will be executed at runtime which
creates performance problems and disturbs console output.
To overcome this problem we should go for assert statement. The main
advantage of assert statement over print() statement is after fixing bug we are not
required to delete assert statements. Based on our requirement we can enable or
disable assert statements.
Hence the main purpose of assertions is to perform debugging. Usully we can
perform debugging either in development or in test environments but not in
production environment. Hence assertions concept is applicable only for dev and
test environments but not for production environment.
Types of assert statements:
There are 2 types of assert statements
1. Simple Version
2. Augmented Version
1. Simple Version:
Syntax: assert conditional_expression
2. Augmented Version:
Syntax: assert conditional_expression,message
conditional_expression will be evaluated and if it is true then the program will be
continued.If it is false then the program will be terminated by raising AssertionError.
By seeing AssertionError, programmer can analyze the code and can fix the
problem.
Examples:1
assert True