Python Notes 1
Python Notes 1
Program:-
Program is a collection of set of instructions to be executed to produce the output
using a special type of compiler or software.
Algorithm:-
The Programmer begins the programming process by analyzing the problem,
breaking it into manageable pieces, and developing a general solution for each
piece called an algorithm.
Flowchart:-
Flow chart is a visually presenting the flow of control through an information
processing systems, the operations performed within the system and the sequence
in which they are performed.
Algorithm:-
Programming Language:-
The language which is used to represent the instructions of a program to execute it
is called a programming language.
Types:-
• Structural/Procedural language:-it is based on structure or
procedures/functions.
ex- c
• Partial object oriented language:-which may or may not use the concepts of
oops to write a program.
ex- c++, php, python
• Fully object oriented language:-without the help of oops we cannot write a
program.
ex- java, .net
• Object based language:- based on objects.
ex- javascript, vbscript
Historical Development of Programming Languages:-
• PASCAL - 1954
• COBOL - 1957
• ALGOL - 1960
• CPL - 1963
• BCPL - 1967
• B - 1970
• C - 1972
• C++ - 1980
• PYTHON – 1980-1990
• JAVA – 1990/1991
• .NET - 1991
• PHP – 1993
• R – 1993
• SCALA - 2003
Features of OOPs:-
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and maintenance
by providing some concepts:
• Class:- class is an user defined data-type which describe about a particular
item or person or place. In OOP languages it is must to create a class
for representing data. Class contains variables for storing data and
functions to specify various operations that can be performed on
data. Class will not occupy any memory space and hence it is only
logical representation of data.
• Object:- object is the instance/copy of the class which describes the
characteristics/behavior of the class. We can create more than one object for
a single class.
• Inheritance:- when one class inherits the features of another class then it is
called inheritance. The main advantage of using inheritance is code
reusability and security. In java there are two types of inheritance; one is
single and another is interface.
• Polymorphism:- Greek word poly means many and morphism means form.
When a single method with same name process to form different-different
operations then it is called polymorphism. There are two types of
polymorphism like compile time polymorphism and run time polymorphism.
• Data encapsulation:- wrapping up of data into a single unit is called
encapsulation. Encapsulation is hiding the functional data from the object
calling it. Integration of data and operations/functions in a class is
Encapsulation. So it is also called data hiding.
• Data abstraction:- It is used to display only necessary and essential features
of an object to the outside world. Choosing of necessary data by
discarding/hiding unnecessary data is called data abstraction.
• Message passing:- when one object copy/pass the messages of it to another
object then it is called as message passing. Passing can be done either
implicitly or explicitly.
What is PYTHON?
Python is a general purpose programming language that is often applied in
scripting roles. So, Python is programming language as well as scripting language.
Python is also called as Interpreted language. Python is derived from many other
languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix
shell and other scripting languages. Python is copyrighted. Like Perl, Python
source code is now available under the GNU General Public License (GPL).
History of PYTHON:-
• Invented in the Netherlands, early 90s by Guido van Rossum.
• Python was conceived in the late 1980s and its implementation was started
in December 1989
• Guido Van Rossum is fan of ‘Monty Python’s Flying Circus’, this is a
famous TV show in Netherlands
• Named after Monty Python
• Open sourced from the beginning.
Features of PYTHON:-
• Python is object-oriented
• Indentation
• It's free (open source)
• It's powerful
• It's portable
• It's mixable
• It's easy to use
• It's easy to learn
Who uses PYTHON?
• Python is being applied in real revenue-generating products by real
companies.
• Google makes extensive use of Python in its web search system, and
employs Python’s creator.
• Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for
hardware testing.
• ESRI uses Python as an end-user customization tool for its popular
GIS(geographic information system) mapping products.
• The YouTube video sharing service is largely written in Python.
PYTHON code execution:-
Python’s traditional runtime execution model: source code we type is translated to
byte code, which is then run by the Python Virtual Machine. Your code is
automatically compiled, but then it is interpreted.
Compiler:-
A compiler is a special program or software which is used to convert source code
to machine code. It is also used to detect errors at the time of compilation of the
program.
Interpreter:-
An interpreter is a computer program that directly executes, ie- performs
instructions written in a programming or scripting language without requiring them
previously to have been compiled into a machine language program.
Byte code:-
Python is a interpreted language and it actually compiles source code to a set of
instructions for a virtual machine, and the python interpreter is an implementation
of that virtual machine. This intermediate format is called byte code.
Running PYTHON:-
Once we're inside the Python interpreter, type in commands at will.
Q1) wap to print yourname?
>>> print("hello world”)
Elements of PYTHON(CH-2)
Variable:-
Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory. Based on the
data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
Assigning value to the variable:-
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal
sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For
example −
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
Taking input from keyboard:-
There are two methods used for taking input:
1. raw_input():-
The raw_input([prompt]) function reads one line from standard input and returns it
as a string (removing the trailing newline).
Q2) wap to input data from keyword?
#!/usr/bin/python
str=raw_input(“enter your data”)
print(“inputted data is”, str)
2. input():-
The input([prompt]) function is equivalent to raw_input, except that it assumes the
input is a valid Python expression and returns the evaluated result to you.
Q3) wap to input data from keyword?
#!/usr/bin/python
str=raw_input(“enter your data”)
print (inputted data is”+ str)
Note:- in python 2.0 we use raw_input() but in python 3.0 we use input().
Python Identifiers:-
A Python identifier is a name used to identify a variable, function, class, module
or other object. An identifier starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores and digits (0 to 9). Python does
not allow punctuation characters such as @, $, and % within identifiers. Python is
a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.
Here are naming conventions for Python identifiers:
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Starting an identifier with a single leading underscore indicates that the
identifier is private.
• Starting an identifier with two leading underscores indicates a strongly
private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Quotations in python:-
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string. The triple
quotes are used to span the string across multiple lines. For example, all the
following are legal-
Ex:-
word=’word’
sentence=”this is a sentence”
paragraph=”””This is a paragraph. It is
made up of multiple lines and sentences.”””
Comments in python:-
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
#!/usr/bin/python
# First comment
print “Hello, Python!” #second comment
Keywords/Reserve-words:-
And exec not
Assert finally or
Break for pass
Class from print
Continue global raise
Def If return
Del import try
Elif In while
Else Is with
Except lambda yield
Python Standard Data-type:-
1. number:-
Number data types store numeric values. Number objects are created when you
assign a value to them.
Ex:-
a=10
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
You can also delete the reference to a number object by using the del statement.
Ex:-
del a
2. string:-
Strings are used to store character type of date within single quote or double quote.
Strings are also called as array of characters. We can store number of lines in a
continuous line by the help of triple quote. The values stored in a string can be
accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the string and working their way to end -1. The plus (+) sign is the
string concatenation operator, and the asterisk (*) is the repetition operator.
Ex:-
str1=’hello’
str2=’world’
print(‘output is’,str1+str2) #helloworld
print(‘output is’,str1*3) #hellohellohello
print('str[0] = ', str[0]) #first character
print('str[-1] = ', str[-1]) #last character
print('str[1:5] = ', str[1:5]) #slicing 2nd to 5th character
print('str[5:-2] = ', str[5:-2]) #slicing 6th to 2nd last character
String Literals:-
1. \a ASCII Bell (BEL)
2. \b ASCII Backspace (BS)
3. \f ASCII Formfeed (FF)
4. \n ASCII Linefeed (LF)
5. \r ASCII Carriage Return (CR)
6. \t ASCII Horizontal Tab (TAB)
7. \v ASCII Vertical Tab (VT)
String formatting specifiers:-
Format Symbol Conversion
%c Character
%o octal integer
name = "John"
age = 23
print("%s is %d years old." % (name, age))
Operator precedence:-
[Link] Operator & Description
.
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are
+@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Control Structure(CH-3)
Decision making statements:-
1. if/simple if statement:-
It consists of a Boolean expression followed by one or more statements. Here we
are able to specify only one condition and one print statement. The demerit of this
statement is it can’t go to the default part.
Syn:-
if expression:
statement(s)
Q12) wap to check for a number whether it is even or not?
n=int(input(“enter a number”))
if n%2==0:
print(“number is even”)
2. if else statement:-
It is followed by an optional else statement, which executes when the Boolean
expression is FALSE. An else statement can be combined with if statement.
An else statement contains the block of code that executes if the conditional
expression in if statement resolves to 0 or a FALSE value.
Syn:-
if expression:
statement(s)
else:
statement(s)
Q13) wap to find the greater number among two number?
a=int(input(“enter first number”))
b=int(input(“enter second number”))
if a>b:
print(“a ia greater”)
else:
print(“b is greater”)
3. nested if statement:-
We can use one if or else if statement inside another if or else if statement(s).
There may be a situation when you want to check for another condition after a
condition resolves to true. In such a situation, you can use the nested if construct.
Syn:-
if expression1:
if expression2:
statement(s)
else:
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)
Q14) wap to for leap year?
y=int(input(“enter a year”))
if y%100!=0:
ify%4==0:
print(“leap year”)
else:
print(“not leap year”)
else:
if y%400==0:
print(“leap year”)
else:
print(“not leap year”)
4. ladder else if statement:-
It is the type of conditional statement where we can specify n no of conditions and
n no of print statements. it is very simple as compare to nested if because here no
nesting of condition is there and we can specify one condition and one print
statement so on.
Syn:-
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Q15) wap to find the greater number among three number?
a=int(input(“enter first number”))
b=int(input(“enter second number”))
c=int(input(“enter third number”))
if a>b and a>c:
print(“a is greatest”)
elif b>a and b>c:
print(“b is greatest”)
else:
print(“c is greatest”)
Q16) Write a program to find the daily wages of a worker according to the
following conditions using ladder else if statement?
duty in hours amount in rupees
within first 8 hours 100 rupees
next 4 hours 20 rs/hr
next 4 hours 40 rs/hr
next 4 hours 60 rs/hr
next 4 hours 80 rs/hr
hr=int(input(“duty in hours”))
if hr>=1 and hr<=8:
amt=100
elif hr>=9 and hr<=12:
amt=100+(hr-8)*20
elif hr>=13 and hr<=16:
amt=180+(hr-12)*40;
elif hr>=17 and hr<=20;
amt=340+(hr-16)*60;
elif hr>=21 and hr<=24:
amt=580+(hr-20)*80;
print(“amount incurred by the worker=”, amt)
Looping statements:-
1. while loop:-
It is otherwise called as top-tested loop or pre-tested loop or entry control loop. In
this type of looping statement first the condition is checked after the statements are
get executed and printed. If the condition is false then no statement is executed or
printed.
Syn:-
while expression:
statement(s)
Q17) Write a program to find all even numbers from 1 to 100?
i=2
while i<=10:
print(i)
i+=2
Q18) Write a program to find the reverse of a number?
num=int(input(“enter an integer number”))
rev=0
while num>0:
rem=num%10
rev=rev*10+rem
num=num//10
print(“\n reverse value=%d” %rev)
Q19) Write a program to check for armstrong number?
num=int(input(“enter an integer number”))
sum=0
temp=num
while num>0:
rem=num%10
sum+=rem**3
num=num//10
if temp==sum:
print(“number is Armstrong”)
else:
print(“number is not Armstrong”)
Q20) Write a program to input a decimal number and convert it into binary?
num=int(input(“enter a decimal number”))
sum=0
prd=1
while num>0:
rem=num%2
sum=sum+rem*prd
prd=prd*10
num=num//2
print(“binary value”, sum)
2. for loop:-
It is the simplest type of looping statement because here all the three parts of the
loop written in one line; so it reduce the line of codes.
Syn:-
for iterating-variable in sequence:
statement(s)
Q21) Write a program to display 1 to n?
n=input(“enter the range”)
for i in range (1,n):
print i
Q22) Write a program to display Fibonacci series?
num=int(input(“enter the range”))
a=0
b=1
print(a)
print(b)
for i in range(2,n):
c=a+b
print(c)
a=b
b=c
Q23) Write a program to find hcf and lcm of two number?
a=int(input(“enter first number”))
b=int(input(“enter second number”))
for i in range(1,a):
if ((a%i==0) and 9b%i==0)):
hcf=i
lcm=(a*b)/hcf
print(“hcf value=”,hcf)
print(“lcm value=”, lcm)
Nested loop:-
When one or more than one loops are nested inside another loop then it is called
nested loop.
Syn:-
while expression:
while expression:
statement(s)
statement(s)
(or)
for expression:
for expression:
statement(s)
statement(s)
Q24) Write a program to print number pyramid series?
for i in range(1,5):
for j in range(1,i+1):
print(j,end="")
print("\r")
Q25) Write a program to print star pyramid series?
for i in range(0,5):
for j in range(0,i+1):
print(“* “,end=””)
print(“\r”)
Q26) Write a program to print full pyramid series?
n=int(input(“enter the range”))
k=2*n-2
for i in range(0,n):
for j in range(0,k):
print(end=” ”)
k=k-1
for j in range(0,i+1):
print(“* “, end=””)
print(“\r”)
Jumping statements:-
1. break:- It terminates the current loop and resumes execution at the next
statement, just like the traditional break statement in C.
Syn:-
if expression:
break
Ex:-
i=1
while i<=10:
if i==5:
break
i=i+1
print(i) o/p-2,3,4,5
Ex:-
i=1
while(i<=10):
if(i==5):
break
print(i)
i=i+1 o/p-1,2,3,4
Ex:-
for i in range (1,10):
if(i==5):
print(i)
break o/p-5
Ex:-
for i in range (1,10):
if(i==5):
break
print(i) o/p-1,2,3,4
Ex:-
for val in "string":
if val == "i":
break
print(val)
print("The end") o/p-str
2. continue:- It returns the control to the beginning of the while loop.
The continue statement rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the loop.
Syn:-
if expression:
continue
Ex:-
for val in "string":
if val == "i":
continue
print(val) o/p-strng
3. pass:- The pass statement is a null operation; nothing happens when it executes.
The pass is also useful in places where your code will eventually go, but has not
been written yet.
Syn:-
Pass
Ex:-
for letter in 'Python': o/p- Current Letter: P
if letter == 'h': Current Letter: y
pass Current Letter: t
print("This is pass block") This is pass block
print("Current Letter :", letter) Current Letter: h
print("Good bye!") Current Letter: o
Current Letter: n
Good bye!
1. Wap to reverse a string without using reverse function?
s=input(“enter a string”)
a=""
i=len(s)
while(i>0):
a+=s[i-1]
i=i-1
print(a)
2. wap to input a string and check whether it is palindrome or not?
s="anil"
s1=""
for i in s:
s1=i+s1
print(s1)
if(s==s1):
print("palindrome")
else:
print("not")
[Link] to input your email id and calculate number of letters, digits and special
symbols?
a=input("enter a string")
al=0
dg=0
ss=0
for i in a:
if((i>='a' and i<='z')and(i>=’A’ and i<=’Z’)):
al=al+1
elif(i>=’0’ and al<=’9’):
dg=dg+1
else:
ss=ss+1
print(al)
print(dg)
print(ss)
4. wap to input a binary number and convert it into its decimal equivalent?
bin=101
dec=0
i=0
while(bin!=0):
rem=bin%10
dec=dec+rem*pow(2,i)
bin=bin//10
i=i+1
print(dec)
5. wap to input a string and calculate the length of the string without using
any function?
a=input("enter a string")
c=0
for i in a:
c=c+1
print(c)
6. wap to input two different strings and display the larger string among them
without using any function?
string1=input("Enter first string:")
string2=input("Enter second string:")
count1=0
count2=0
for i in string1:
count1=count1+1
for j in string2:
count2=count2+1
if(count1<count2):
print("Larger string is:")
print(string2)
elif(count1==count2):
print("Both strings are equal.")
else:
print("Larger string is:")
print(string1)
7. wap to print the series like:
*
**
***
****
*****
****
***
**
*
n=5;
for i in range(n):
for j in range(i):
print (“* “, end=””)
print('')
for i in range(n,0,-1):
for j in range(i):
print(“* “, end=””)
print(“”)
8. wap to print the series like:
c
co
com
comp
compu
comput
compute
computer
s="computer"
for i in range(1,9):
for j in range(0,i):
print(s[j],end="")
print("\r")
9. wap to reverse a string without using library function?
s="anil"
s1=""
for i in s:
s1=i+s1
print(s1)
10. wap to input a full string and display it in shortcut?
s=input("enter a string")
print(s[0],end="")
for i in range(0,len(s)):
if s[i]==" ":
print(".",s[i+1],end="")
print(".")
11. Wap to input an integer number and check whether it is a disarium
number or not?
length = 0;
sum=0
n=175
temp=n
num=n
while(n != 0):
length = length + 1;
n = n//10;
while(num > 0):
rem = num%10;
sum = sum + int(rem**length);
num = num//10;
length = length - 1;
if(sum == temp):
print(" is a disarium number");
else:
print(" is not a disarium number");
Array(CH-4)
An array is a special variable, which can hold more than one value at a time. An
array can hold many values under a single name, and you can access the values by
referring to an index number.
Type
C Type Python Type Minimum size in bytes
code
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
%% A % character %
Function(CH-5)
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high
degree of code reusing. A function is a block of code which only runs when it is
called. You can pass data, known as parameters, into a function. A function can
return data as a result.
Defining a function:-
• Function blocks begin with the keyword def followed by the function name
and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the
documentation string of the function or doc-string.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back
an expression to the caller. A return statement with no arguments is the
same as return None.
Syn:-
def function-name(parameters):
statement (s)
return[expression]
Calling a function:-
All parameters (arguments) in the Python language are passed by reference. It
means if you change what a parameter refers to within a function, the change also
reflects back in the calling function.
Ex:-
#!/usr/bin/python
def hello(a):
“hello students”
[Link]([1,2,3,4]);
print “values inside the function:”,a
return
a=[10,20,30];
hello(a);
print ”values outside the functions:”,a
Here, we are maintaining reference of the pass object and appending values in the
same object.
Function arguments:-
1. required arguments:-
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly
with the function definition.
Ex:-
#!/usr/bin/python
def hello(str):
“hello students”
print str
return;
hello()
2. keyword arguments:-
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
Ex:-
#!/usr/bin/python
def hello(str):
“hello students”
print str
return;
hello(str=”my string”)
3. default arguments:-
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
#!/usr/bin/python
def hello(name,age=20):
“hello students”
print “Name:”, name
print “Age:”, age
return;
hello(age=30,name=”anil”)
hello(name=”anil”)
4. variable-length arguments:-
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and
are not named in the function definition, unlike required and default arguments.
#!/usr/bin/python
def hello(arg1,*vartuple):
“hello students”
print “Output is:”
print arg1
for var in vartuple:
print var
return;
hello(30)
hello(50,60,70)
Modules:-
A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use. A module is a
Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnable code.
Creating a module:-
Ex:- [Link]
def abc(name):
print(“hello,”+name)
Use a module:-
Ex:-
import mymodule
[Link](“anil”)
File Handling(CH-6)
File:-
A file represents a sequence of bytes which is used to store information. Python
provides access on high level functions as well as low level (OS level) calls to
handle file on our storage devices.
Types:-
• Text file:- Text files are the normal .txt files that you can easily create using
Notepad or any simple text editors. When you open those files, you'll see all
the contents within the file as plain text. You can easily edit or delete the
contents. They take minimum effort to maintain, are easily readable, and
provide least security and takes bigger storage space.
• Binary file:- Binary files are mostly the .bin files in your computer. Instead
of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a
better security than text files.
File operation:-
1. Opening a file:-
The open() function takes two parameters; filename, and mode. There are four
different methods (modes) for opening a file:
Syn:-
file-object-name=open(“path with [Link]”,”mode”)
[Link] Modes & Description
.
1 R
Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
2 Rb
Opens a file for reading only in binary format. The file pointer is
placed at the beginning of the file. This is the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at
the beginning of the file.
4 rb+
Opens a file for both reading and writing in binary format. The file
pointer placed at the beginning of the file.
5 W
Opens a file for writing only. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
6 Wb
Opens a file for writing only in binary format. Overwrites the file if
the file exists. If the file does not exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file
if the file exists. If the file does not exist, creates a new file for
reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
9 A
Opens a file for appending. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.
10 Ab
Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append mode.
If the file does not exist, it creates a new file for writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If
the file does not exist, it creates a new file for reading and writing.
12 ab+
Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing.
13 X
will create a file, returns an error if the file exist
2. Closing a file:-
The close() method of a file object flushes any unwritten information and closes
the file object, after which no more writing can be done.
Syn:-
[Link]()
3. Reading a file:-
The open() function returns a file object, which has a read() method for reading the
content of the file:
a. Read():- read all the characters from a file.
Ex:-
f=open(“d:\\[Link]”,”r”);
print([Link]())
b. Read(size):- read the characters up-to specified size.
Ex:-
f=open(“D:\\[Link]”,”r”);
print([Link](5)) #reading part of a file upto first 5 characters
c. Readline():- read a single line from the file only.
Ex:-
f=open(“d:\\[Link]”,”r”)
print([Link]())
d. readlines():- read all the characters from the file and display as a list
followed by \n for each line break.
4. Writing to a file:-
To write to an existing file, you must add a parameter to the open() function:
Ex:-
f=open(“d:\\[Link]”,”w”)
[Link](“hello anil”)
[Link]() # it is necessary to close the file.
Ex:-
f=open(“d:\\[Link]”,”w”)
a=input(“”)
[Link](a)
[Link]() # it is necessary to close the file.
5. Renaming a file:-
Ex:-
import os
[Link](“d:\\[Link]”,”d:\\[Link]”)
6. Removing a file:-
Ex:-
import os
[Link](“d:\\[Link]”)
7. Making a directory:-
Ex:-
import os
[Link](“d:\\anil”)
8. Changing a directory:-
Ex:-
import os
[Link](“/new folder/swarnaa”)
9. Removing a directory:-
Ex:-
import os
[Link](“anil”);
Exception Handling(CH-7)
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. Exceptions are the errors
which are occur during program execution process. There are two types of
exceptions occur inside the program. That are:
• Compile time error:- the errors which are occurred at the time of compilation
of the program are called compile time errors. These are also called as
syntax error.
Ex:- statement missing, termination error etc.
• Runtime error:- the errors which are occurred at the time of running the
program are called runtime errors. There are two types of runtime exceptions
available like:
• Synchronous exception:- the exceptions which are under the control
of the programmer/computer are called synchronous exceptions. Ex:-
loop overflow, zero divide, number format error.
• Asynchronous exception:- the exceptions which are beyond the
control of the programmer/computer are called asynchronous
exceptions. Ex:- system crash, hard-disk failure etc.
List of Standard Exceptions:-
[Link] Exception Name & Description
.
1 Exception
Base class for all exceptions
2 StopIteration
Raised when the next() of an iterator does not point to any object.
3 SystemExit
Raised by the [Link]() function.
4 StandardError
Base class for all built-in exceptions except StopIteration and
SystemExit.
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric
types.
9 AssertionError
Raised in case of failure of the Assert statement.
10 AttributeError
Raised in case of failure of attribute reference or assignment.
11 EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
12 ImportError
Raised when an import statement fails.
13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
14 LookupError
Base class for all lookup errors.
15 IndexError
Raised when an index is not found in a sequence.
16 KeyError
Raised when the specified key is not found in the dictionary.
17 NameError
Raised when an identifier is not found in the local or global namespace.
18 UnboundLocalError
Raised when trying to access a local variable in a function or method
but no value has been assigned to it.
19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20 IOError
Raised when an input/ output operation fails, such as the print statement
or the open() function when trying to open a file that does not exist.
21 IOError
Raised for operating system-related errors.
22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.
24 SystemError
Raised when the interpreter finds an internal problem, but when this
error is encountered the Python interpreter does not exit.
25 SystemExit
Raised when Python interpreter is quit by using the [Link]() function.
If not handled in the code, causes the interpreter to exit.
26 TypeError
Raised when an operation or function is attempted that is invalid for the
specified data type.
27 ValueError
Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
28 RuntimeError
Raised when a generated error does not fall into any category.
29 NotImplementedError
Raised when an abstract method that needs to be implemented in an
inherited class is not actually implemented.
Handling an Exception:-
Syn:-
try:
code here;
except exception-name:
exceptional message
except exception-name:
exceptional message
else:
default message
finally:
message
Ex:-
try:
f=open(“[Link]”)
[Link](“hello anil”)
except:
print(“something went wrong with the file”)
finally:
[Link]()
Regular Expression and Pattern Matching:-
Regular expression is a special text string used for describing a search pattern. It is
extremely useful for extracting information from text such as code, files, log,
spreadsheets or even documents. We need a package called “import re”.
"^": This expression matches the start of a string
"w+": This expression matches the alphanumeric character in the string(if
you remove +sign from the w+, the output will change, and it will only give
the first character of the first letter)
r'^$' : is a regular expression that matches an empty line. This looks like a
regular expression (regex) commonly used in Django URL
[Link] 'r' in front tells Python the expression is a raw string. In a
raw string, escape sequences are not parsed. For example, '\n' is a single
newline character. But, r'\n' would be two characters: a backslash and an
'n'.Raw strings are handy in regex, in which the backslash is used often for
its own purposes.
1. match():-
import re
l=["anil55 abc", "anil55 axy", "anil xyz"]
for a in l:
b=[Link]("(a\w+)\W(a\w+)",a)
if b:
print(([Link]()))
2. search():-
import re
a=['software testing', 'guru99']
b='software testing is fun?'
for i in a:
print((i,b),end=' ')
if [Link](i,b):
print('found')
else:
print('not')
3. findall():-
import re
a='abc@[Link], xyz@[Link], pqr@[Link]'
b=[Link](r'[\w\.-]+@[\w\.-]+',a)
for c in b:
print(c)
Ex:-
import re
xx = "guru99,education is fun"
r1 = [Link](r"^\w", xx)
print(r1)
Ex:-
import re
xx = "guru99,education is fun"
r1 = [Link](r"^\w+", xx)
print(r1)
Ex:-
import re
pattern = '^a...s$'
test_string = 'abyss'
result = [Link](pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
Ex:-
import re
x = "guru99,education is fun"
r1 = [Link](r"^\w", xx)
print(r1)
Ex:-
import re
x = "guru99,education is fun"
r1 = [Link](r"^\w+", xx)
print(r1)
Class and Object:-
Class:-
A class is an user-defined datatype in java which can be created by the help of
class keyword. It is also the collection of dissimilar type of related data. It
describes about a particular place or person. A class is also called as an entity
which contains different data. A class consists of two components.
1. Datamember:- these are just like variables to hold data. Datamembers are
declared at the top of the class declaration preceeded by datatype means
which type of data it can hold. Ex:- roll,address, a etc.
2. Methods:- these are nothing but the member functions just like in c which
are used to operate the datamembers inside the class program. Methods must
preceeded by a return type to say whether it returns a value or print
something. Ex:- def show(), def get() etc.
Syn for class creation:-
class Classname:
data member(s)
def metodname(arguments):
statement(s)
Object:-
Object is the instance of a class. A class needs to be instantiated if we want to use
the class attributes in another class or method. A class can be instantiated by
calling the class using the class name.
Syntax for object creation:-
objectname=classname(arguments)
Ex:-
class Employee:
id = 101
name = "Anil"
def display (self):
print("ID: %d \nName: %s"%([Link],[Link]))
emp = Employee()
[Link]()
Use of self parameter:-
Self parameter is a reference to the current instance of the class, and is used to
access variables that belong to the class. It does not have to be named self, you can
call it whatever you like, but it has to be the first parameter of any function in the
class.
Use of __init__() method:-
Ex:-
All classes have a function called __init__(), which is always executed when the
class is being initiated. Use the __init__() function to assign values to object
properties, or other operations that are necessary to do when the object is being
created. This method is called automatically every time the class is being used to
create a new object.
Ex:-
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print([Link])
print([Link])
Object method:-
Objects can also contain methods. Methods in objects are functions that belongs to
the object.
Ex:-
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
Deleting object property:-
Ex:-
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
del [Link]
print([Link])
Deleting object:-
Ex:-
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
del p1
print(p1)
Constructor:-
A constructor is a special type of member function in python programming. A
constructor name is same as class name. A constructor doesn’t return a value nor it
has any return type. A constructor is automatically called when an object is created
inside the class program which is the most important advantage of it. A constructor
may or mayn’t have argument/parameter. We can declare more than one
constructor inside a class. In python, the method __init__ simulates the constructor
of the class. This method is called when the class is instantiated. We can pass any
number of arguments at the time of creating the class object, depending upon
__init__ definition. It is mostly used to initialize the class attributes. Every class
must have a constructor, even if it simply relies on the default constructor.
Types:-
1. default constructor:-
If a constructor doesn’t consists of any argument or parameter associated with its
function call or anywhere then it is called default constructor. It only initializes the
variable/data-member values inside its body part.
Ex:-
class Student:
count = 0
def __init__(self):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])
2. Parameterized constructor:-
If a constructor does consists of any argument or parameter associated with its
function call or anywhere then it is called parameterized constructor. It passes the
value of its function parameter to the instance variable for further processing.
Ex:-
class Employee:
def __init__(self,name,id):
[Link] = id
[Link] = name
def display (self):
print("ID: %d \nName: %s"%([Link],[Link]))
emp1 = Employee("John",101)
emp2 = Employee("David",102)
[Link]()
[Link]()
Inheritance:-
It is the concept by which one class derives the features of another class. Means for
creating an inheritance program we must require at least two classes. One is called
base/existing/parent/super class where another is called child/sub/derived class.
Child class derives the features of parent class; hence we always create object for
child class only. The main advantage of using inheritance is code reusability.
Another thing is that if we use inheritance then the parent class data must be
protected so that the selected classes can use only parent class data. In python, a
derived class can inherit base class by just mentioning the base in the bracket after
the derived class name.
Types:-
1. single inheritance:-
When a single derived class inherits the features of a single base class then it is
called single inheritance. In single inheritance we can have maximum and
minimum 2 classes.
Structure:- Example:-
Parent
Parentclass
class Father
Syn:-
class derived-class-name (base-class-name):
statement(s)
Ex:-
class Hello:
def show(self):
print(“welcome to python")
class Hii(Hello):
def disp(self):
print("welcome to oops")
d = Hii()
[Link]()
[Link]()
2. Multilevel inheritance:-
When one derived class is derived from another derived class and that derived
class is again derived from a parent class by maintaining a level then it is called as
multilevel inheritance.
Structure:- Example:-
Syn:-
class class1:
statement(s)
class class2(class1):
statement(s)
class class3(class2):
statement(s)
Ex:-
class Father:
def disp(self):
print”this is father class")
class Mother(Father):
def show(self):
print("this is mother class")
class Son(Mother):
def display(self):
print("this is son class")
d = Son()
[Link]()
[Link]()
[Link]()
3. Multiple inheritance:-
It is the type of inheritance where we can use more than one base class and one
child class; means when a single derived class is derives the features of more than
one base class then it is called as multiple inheritance.
Structure:- Example:-
Syn:-
class Base1:
statement(s)
class Base2:
statement(s)
.
.
.
class BaseN:
statement(s)
class Derived(Base1, Base2, ...... BaseN):
statement(s)
Ex:-
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))
Use of issubclass() method:-
The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second class,
and false otherwise.
Ex:-
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Use of isinstance() method:-
The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.
Ex:-
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Polymorphism:-
Greek word poly means many and morphism means form. Polymorphism is the
ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a
child class object. There are two types of polymorphism in java: compile time
polymorphism and runtime polymorphism. We can perform polymorphism in java
by method overloading and method overriding.
Types:-
1. Compile time polymorphism:-
The polymorphism which is occurred at the time of compilation of the program is
called compile time polymorphism. The best example of compile time
polymorphism in python is to overload a static method. Overloading happens in
single class.
Method overloading:-when a single class calls same function for multiple times
with different-different operations then it is called method overloading. Here
method name must be same but type argument must be different.
Ex:-
class Hello:
def show(self,name=None):
if name is not None:
print(“welcome”+name)
else:
print(“welcome”)
obj=Hello()
[Link]()
[Link](“anil”)
2. Runtime polymorphism:-
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call
to an overridden method is resolved at runtime rather than compile-time. In this
process, an overridden method is called through the reference variable of a super
class. The determination of the method to be called is based on the object being
referred to by the reference variable. Method overriding is the example of runtime
polymorphism.
Method overriding:-
When the parent class method name is same in child classes then it is called
method overriding. Parent class method is defined in the child class with some
specific implementation.
Ex:-
class One:
def get(self):
return 5;
class Two(One):
def get(self):
return 10;
class Three(One):
def get(self):
return 15;
a1 = One()
a2 = Two()
a3 = Three()
print("First value is:",[Link]());
print("Second value is:",[Link]());
print("Third value is:",[Link]());