Python BDPS
Python BDPS
Introduction
Python is a very powerful high-level,general-purpose, object-oriented
programming language created by Guido van Rossum in 1989.
History of Python
The Python programming language was conceived in the late
1980s, and its implementation was started in December 1989 by
Guido van Rossum at CWI(Centrum Wiskunde & Informatica) in the
Netherlands as a successor of ABC programming language. Python
was published in 1991.
Installing Python
To install Python, you will need to download its most recent
distribution from the following URL: www.python.org. Let’s have
a look at the steps for installing Python on Microsoft Windows.
In the next dialog, you will be asked for the destination folder where
you want to install Python files. The wizard also displays a folder name by
default that represents the Python version being installed. Select the Next
button to continue. The next dialog is to specify the Python features (i.e.,
the components) that you want to install, as shown in Figure
Selecting Python components to install.
The installer program will copy the Python files to the selected folder,
and you will be asked to select the Finish button to exit the installation
wizard.
Character set:
Any Programming language is required to represent its
characters with the help of character set. An ASCII character set
is used to represent characters up to 3 rd generation
languages(c/c++). An ASCII character set supports 8 bit
characters. The number of characters that can be represented by
this coding system is limited to 256 only. In order to extend
ASCII coding system, an universal coding system (UNICODE)
is introduced. Python adapted this coding system for
representing its characters.
Keywords
Keywords are the reserved words in Python. There are 35 keywords in
Python 3.7.1 This number can vary in different versions of Python.
You can always get the list of keywords in your current version by typing
the following in the prompt.
Eg:
>>> 2*10
20
>>> 3+4+9
16
>>> 2**3
8
Data Types in Python
Python has a rich set of fundamental data types. The operations on an
object depend on its data type.
–2,147,483,648 to 2,147,483,647`
Long Integers:
It has unlimited, subject to the memory limitations of the computer.
Strings:
Sequences of Unicode characters. A string can be represented either
Single quotes (or) double quotes.
Boolean:
It can hold only one of two possible values: True or False.
Complex Number:
A complex number has a real and an imaginary component, both
represented by float types in Python. For instance, 2+3j is a complex
number, where 3j is the imaginary component and is equal to
√-9 (√9 × √−1 = 3i or 3j)
Eg1:
>>> complex(2,3)
(2+3j)
>>> type(10.0)
<class 'float'>
>>> type(‘abc’)
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(2+3j)
<class 'complex'>
Variables
Variables are used for storing data in a program. Therefore, by
assigning different data types to variables(you can store letters,
numbers, or words).
Rules for creating variable names(Identifiers)
1. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore ( _ ).
2. An identifier cannot start with a digit. identifier must start with a
letter or an underscore
3. Keywords cannot be used as identifiers.
4. Identifier can be of any length.
For example
A = 10
value = 10.0
st_value="Hello World!"
You can see in the preceding examples the variable can be a single
character or a word or words connected with underscores.
Multiple Assignment
Python allows you to assign a single value to several variables.
For example
a=b=c=1
Here, an integer value 1 is assigned all the three variables.
For example –
a,b,c=1,2,”Hello”
Here, two integer values 1 and 2 are assigned to variables a and b
respectively, and a string "Hello" is assigned to the variable c.
print(1,2,3,4)
Output: 1 2 3 4
print(1,2,3,4,sep='*')
Output: 1*2*3*4
print(1,2,3,4,sep='#',end='$')
Output: 1#2#3#4$
Eg:2
print('Hello', 'welcome to python')
output: Hello welcome to python
It display the two strings on the same line separated by a space
print('Hello'+ 'welcome to python')
output: Hellowelcome to python
It display the two strings on the same line without any space in
between the two strings.
Here the curly braces {} are used as placeholders. We can specify the
order in which it is printed by using index numbers.
Eg:
print('I love {0} and {1}'.format('bread','butter'))
Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
Output: I love butter and bread
Comments:
Comments lines are for documentation purposes and
these lines are ignored by the interpreter.
# - Single line comment
’’’
---------------------
--------------------- Multi line comment
----------------------
’’’
Format strings
We can use format strings in print() function like printf() style used
in ‘C’ language.
The list of format Strings
Eg:
Emp.py
eno=100
grade='A'
ename='HHHH'
salary=20000.00
print ("Eno :%d" %(eno))
print ("Grade :%c" %(grade))
print ("Ename :%s" %(ename))
print ("salary :%.2f" %(salary))
Escape Sequences
Python uses some backslash characters in output functions for formatting the
output. These characters are called as Escape sequence characters. In these
characters it consists of two characters ,But it is treated as a single character
Eg:
print('Hello \n Welcome to Python Programming')
print('Name\tEmail Address\tContact Number')
python Input
We want to take the input from the user, We use input() function.
Syntax :
input([prompt])
1) int(x)
This function converts any data type to integer.
2)float(x) :
This function is used to convert any data type to a floating point
number
Con1.py
s = input(‘Enter any string :”)
c = int(s)
print ("After converting to integer : ",c)
c = float(s)
print ("After converting to float : ",c)
3. ord(x) :
converts a character to integer.
4.chr(x) :
Converts an integer to a character
5. str(x) :
Converts integer (or) float into a string.
6.complex(real,imag) :
Converts real numbers to complex number
Con2.py
c = ord('d')
print ("After converting character to integer :",c)
c = chr(65)
print ("After converting character to integer :",c)
c = str(123)
print ("After converting integer to string :",c)
c = complex(1,2)
print ("After converting integer to complex number :",c)
Python Indentation
Most of the programming languages like C, C++and Java use braces { }
to define a block of code. Python uses whitespace indentation to define
blocks rather than curly braces . A code block (body of
a function, loop etc.) starts with indentation and ends with un-indentation
line.
Continuation Lines
You can join two adjacent lines,the first ends with a backslash (\).
The indentation is not applied to continuation lines.
Eg:
print('Hello World! \
Welcome to \
PYTHON.')
Python Operators
Operator :
Operator is special symbol in Python and it performs a particular
operation.
Operand :
The value on which the operator acts is called as operand.
Python has a number of operators which are classified below.
1)Arithmetic operators
2)Relational operators
3)Logical operators
4)Bitwise operators
5)Assignment operators
6)Special operators
a. Identity operators
b. Membership operators
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
Ari.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('Addition :',a+b)
print('Subtraction :',a-b)
print('Multiplication :',a*b)
print('Division :',a/b)
print('Modulus :',a%b)
print('Floor Division :',a//b)
print('Exponent :',a**b)
round()
Python provides an inbuilt function round() ,which rounds precision
digits of floating point number.
Syntax:
round(floating number, no of precision digits)
>>>round(10.639 , 2)
10.64
2)Relational operators
These are used to test the relation between 2 values or 2 expressions.
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Logical operators :
These are used to combine the result of 2 or more expressions.
and Logical AND
or Logical OR
not Logical NOT
Bit-wise Operators :
These operators are used for manipulation of data at bit level.
Bit-wise logical operators :
These are used for bit-wise logical decision making.
Bit-wise logical OR
Eg : int a=5,b=6;
a=5 - 1 0 1
b=6 - 1 1 0
1 0 1
1 1 0
----------------------
a&b : 1 0 0 =4
----------------------
1 0 1
1 1 0
----------------------
a|b : 1 1 1 =7
----------------------
1 0 1
1 1 0
----------------------
a^b : 0 1 1 =3
----------------------
Bit1.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('a & b :',a&b)
print('a | b :',a|b)
print('a ^ b :',a^b)
Bit2.py
a=4
b=a<<2
c=a>>1
print('a :',a)
print('b :',b)
print('c :',c)
Assignment Operators :
These operators are used to assign values to variables.
Simple assignment :
=
compound assignment
+=
-=
*=
/=
//=
%=
**=
etc.
n=10, if we want to add 5 to n then we will give
n=n+5
(or)
n+=5 which is compound assignment.
Eg:
>>> n=10
>>> n
10
>>> n+=5
>>> n
15
Special operators
Python language offers two types of special operators. They are
1.identity operators
2.membership operators
Identity operators
‘is’ and ‘is not’ are the identity operators in Python. They are used to check
two values or variables.
eg:
>>> a=10
>>> b=10
>>> c=20
>>> a is b
True
>>> a is not c
True
Membership operators
‘in’ and ‘not in’ are the membership operators in Python.
They are used to test whether a value or variable is found in a
sequence(string, list, tuple, and set).
>>> st='abcd'
>>> 'a' in st
True
>>> 'k' not in st
True
>>> x='a'
>>> x in st
True
2. if-else statement
It is an extension of simple if statement.
if a> b :
max=a
else :
max=b
print("Maximum value :",max)
if-else1.py
n=int(input("Enter any Number :"))
if n%2==0 :
print("Given Number is Even")
else :
print("Given Number is Odd")
3. Nested if statement :
Using a if statement within another if is called as nested if. If a series of
decisions are involved, we use nested if statement.
Form : 1
if condition-1 :
if condition-2 :
………….
………..
If condition-n :
Statements
Form : 2
if condition-1 :
if condition-2 :
Statement-1
else :
Statement-2
else :
If condition-3 :
Statement-3
else :
Statement-4
4. if-elif-else statement
This statement is also used for a series of decisions are involved.
Syntax:
if condition-1 :
statements-1
elif condition-2 :
statements-2
………………….
………………….
elif condition-n:
statements-n
else :
else block - statements
Stu.py
sno=int(input("Enter Student Number :"))
sname=input("Enter Student Name :")
print("Enter Marks in C,C++ ,Java and Python ");
c=int(input())
cpp=int(input())
java=int(input())
python=int(input())
tot=c+cpp+java+python
avg=tot/4
if c>=50 and cpp>=50 and java>=50 and python>=50 :
result='Pass'
if avg >=90:
grade='A+'
elif avg>=70:
grade='A'
else :
grade='B'
else :
result='Fail'
grade='-'
print(" RESULT ")
print("----------------------------------")
print("Sudent Number :",sno)
print("Sudent Name :",sname)
print("Marks in C :",c)
print("Marks in C++ :",cpp)
print("Marks in Java :",java)
print("Marks in Python :",python)
print("Total Marks in :",tot)
print("Average :%.2f" %(avg))
print("Result :",result)
print("Grade :",grade)
print("----------------------------------")
While loop
It is a conditional controlled loop statement in python.
Syntax:
while condition :
statements
In this loop first the condition will be evaluated. If it is true, then the
statement block will be executed. After the execution of statements, the
condition will be evaluated once again, if it is true then the statement block
will be executed once again. This process of repeated execution continues
until the condition becomes false.
range(x):
Returns a list whose items are consecutive integers from 0 to x-1 .
range(x, y):
Returns a list whose items are consecutive integers from x to y-1 .
range(x, y, step):
Returns a list of integers from x to y-1 , and the difference between each
successive value is the value defined by step.
#To Display Even and Odd numbers from 1 to given number using for loop
n=int(input("Enter any Number : "))
print("\nEven number from 1 to",n)
for i in range(2,n+1,2):
print(i,end='\t')
Infinite Loops
An infinite loop is a loop that executes its block of statements repeatedly
until the user forces the loop to quit2E
break.py
k=1
while True :
print (k,end='\t')
k=k+1
if(k>10):
break
Output:
1 2 3 4 5 6 7 8 9 10
The following program prints numbers from 1 to 10 except for the values 4
and 7
continue.py
k=1
while k <=10 :
if k==4 or k==7:
k=k+1
continue
print (k,end=’\t’)
k=k+1
Output:
1 2 3 4 5 6 8 9 10
pass.py
k=1
while k <=10 :
if k==7:
pass
else:
print (k,”\t”,end=’’)
k+=1
Output:
1 2 3 4 5 6 8 9 10
Nested loops
Using a loop statement within another loop is called as nested loops.
patteren2
n = int(input("Enter the value of n : "))
s=n*2
for i in range(1,n) :
for k in range(1,s):
print(end=" ")
j=1
while j<=i :
print('*',end=" ")
j=j+1
print()
s=s-2
patteren3
2) Sets
3) Dictionaries
Note: Sets and Dictionaries are containers for sequential
data.
Lists
A list is a data structure in Python that is mutable (changeable)
sequence of elements. Each element or value that is inside of a
list is called an item. A list is created by placing all the items
(elements) inside a square brackets, separated by comma. It can
have any number of items and they may be of different types
(integer, float, string etc.).
Syntax:
List_Name = [item-1,item-2,………,item-n]
# empty list
a=[]
# list of integers
a = [1, 2, 3]
>>> a = ['P','Y','T','H','O','N']
>>> a
['P', 'Y', 'T', 'H', 'O', 'N']
>>> print(a[2])
T
>>> print(a[5])
N
Sub lists
>>> a=[[1,2,3],[100,200,300]]
>>> a
[[1, 2, 3], [100, 200, 300]]
>>> print(a[0][1])
2
>>> print(a[1][2])
300
Negative indexing
Python allows negative indexing . The index of -1 refers to the last item, -2 to the
second last item and so on.
>>> a = ['P','Y','T','H','O','N']
>>> print(a[-1])
N
>>> print(a[-6])
P
Slicing
We can access a range of items in a list by using the slicing operator : (colon).
Syntax:
List_name[x:y]
It displays list Items from x to y-1;
>>> a=[10,20,30,40,50,60,70,80,90,100]
# elements 3rd to 5th
>>> print(a[2:5])
[30, 40, 50]
>>> del a
>>> a
NameError: name 'a' is not defined
List Methods
Some Methods are available with list object in Python programming
They are accessed as listobject .method()
1)append
Add an element to the end of the list
Syntax:
append(x)
x - element
Eg:
>>>a=[1,2,3]
>>> a
[1, 2, 3]
>>> a.append(4)
>>>a
[1, 2, 3, 4]
#Write a python script to accept a List from key board and display list elements
List1.py
n=int(input("Enter No of Elements :"))
a=[]
print("Enter Elements")
for i in range(n):
a.append(int(input()))
print("Given Elements :",a)
2)Insert
Insert an Element at given position(index).
Syntax:
insert(i, x)
i – index
x- element
Eg:
>>> a = [1,2,4,5,6]
>>> a
[1, 2, 4, 5, 6]
>>> a.insert(2,3)
>>> a
[1, 2, 3, 4, 5, 6]
Note: If the specified index is not available ,the element will be inserted at
last index.
>>> a.insert(20,100)
>>> a
[1, 2, 3, 4, 5, 6, 100]
Remove
Removes an Element from the list
Syntax:
remove(x)
x – element
Note:
1.It removes first occurrence of the specified element
2.if there is no such item, it displays an error
Eg:
>>> a = [1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.remove(2)
>>> a
[1, 3, 4, 5]
>>> a.remove(8)
ValueError: list.remove(x): x not in list
pop
Removes and returns an element at the given index in the list, and return it. If no
index is specified, It removes and returns the last item in the list.
Syntax :
Pop( [i] )
i – index
Eg:
>>> a = [1,2,3,4,5,6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.pop(3)
4
>>> a
[1, 2, 3, 5, 6]
>>> a.pop()
6
>>> a
[1, 2, 3, 5]
>>> a.pop(10)
IndexError: pop index out of range
clear
Removes all elements from the list.
Syntax:
clear()
Eg:
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.clear()
>>> a
[]
index
Returns the index of the First matched Element
Syntax:
index(x)
x – element
Eg:
>>> a=[1,2,5,2,8]
>>> a
[1, 2, 5, 2, 8]
>>> a.index(2)
1
>>> a.index(10)
ValueError: 10 is not in list
count
Return the number of times Element appears in the list.
Syntax:
count(x)
x – element
>>> a=[1,2,4,2,6,2]
>>> a
[1, 2, 4, 2, 6, 2]
>>> a.count(2)
3
>>> a.count(8)
0
extend
Extend the list by appending all the Elements from another list
Syntax:
extend(another list)
Eg:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=a+b
>>> c
[1, 2, 3, 4, 5, 6]
Sort
Sort Elements in a list in ascending or descending order.
Syntax:
sort([reverse=False])
sort() – ascending
sort(reverse=True) - descending
Eg:
>>> a=[5,2,6,1,4,3]
>>> a
[5, 2, 6, 1, 4, 3]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.sort(reverse=True)
>>> a
[6, 5, 4, 3, 2, 1]
#To accept a group of elements and display in Ascending order and Descending order
List_sort.py
Buit-in functions
1)len(list)
Gives the total length of the list.
2)max(list)
Returns the maximum element in the list.
3)min(list)
Returns the minimum element in the list.
4)sorted(list)
Returns the sorted list
Eg:
List_funs.py
n=int(input("Enter No of Elements :"))
a=[]
print("Enter Elements")
for i in range(n):
a.append(int(input()))
print("Given List :",a)
print("Length :",len(a))
print("Max Element :",max(a))
print("Min Element :",min(a))
print("Sorted List :",sorted(a))
Tuples
A tuple is a sequence of immutable Python objects. Tuples are just like
lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
Note: parentheses brackets are optional for Tuples
Syntax:
Tuple_name=(item-1,item-2,…,ietm-n)
Eg:
>>> tup1=('hari','ravi',100,200)
>>> tup1
('hari', 'ravi', 100, 200)
>>> tup2=(1,2,3,4,5)
>>> tup2
(1, 2, 3, 4, 5)
>>> t=tuple('PYTHON')
>>> t
('P', 'Y', 'T', 'H', 'O', 'N')
>>> print(t[0])
P
>>> print(t[1:3])
('Y', 'T')
>>> a=(1,2,3)
>>> b=(4,5,6)
>>> c=a+b
>>> c
(1, 2, 3, 4, 5, 6)
Buit-in functions
1)len(tuple)
Gives the total length of the tuple.
2)max(tuple)
Returns the maximum element in the tuple.
3)min(tuple)
Returns the minimum element in the tuple.
4)sorted(tuple)
Returns the sorted list of given tuple
Tup_fun.py
a=(3,6,1,8,4,5)
print("Given Tuple :",a)
print("Length :",len(a))
print("Max Element :",max(a))
print("Min Element :",min(a))
print("Sorted List :",sorted(a))
Strings
Eg:
st=' Hello World! '
st="Hello World!"
String functions
str:
Returns a string representation of the specified object.
Syntax:
str(x)
x – object of any datatype
eg:
>>> str(123)
'123'
>>> str(10.345)
'10.345'
max():
Returns the maximum alphabetical character in the string.
eg:
>>> max("ABCDEFGH")
'H'
min():
Returns the minimum alphabetical character in the string.
eg:
>>> min("ABCDEFGH")
'A'
len():
Counts and returns the number of characters in the string.
eg:
>>> len("ABCD")
4
sorted():
Returns the List representation string’s characters in sorted order.
>>> st="CFADEB"
>>> sorted(st)
['A', 'B', 'C', 'D', 'E', 'F']
String Methods
lower():
Returns the string converted to lowercase.
eg:
>>> st="WelCome"
>>> st.lower()
'welcome'
upper():
Returns the string converted to uppercase.
eg:
>>> st="WelCome"
>>> st.upper()
'WELCOME'
swapcase():
Returns the string with uppercase characters converted to lowercase and
lowercase characters converted to uppercase .
Eg:
>>> st="WELcome"
>>> st
'WELcome'
>>> st.swapcase()
'welCOME'
title():
Returns the string with first character of each word converted to uppercase
characters and the rest all characters in lowercase.
eg:
>>> st="welcome to python programming"
>>> st
'welcome to python programming'
>>> st.title()
'Welcome To Python Programming'
isalpha():
Returns True if all characters in the string are alphabetic, otherwise returns
False.
eg:
>>> st="abcd"
>>> st.isalpha()
True
>>> st="123abcd"
>>> st.isalpha()
False
isdigit():
Returns true if all characters in the string are digits, otherwise returns false.
eg:
>>> st="123"
>>> st.isdigit()
True
>>> st="123abcd"
>>> st.isdigit()
False
islower():
Returns true if all characters in the string are lowercase, otherwise returns false.
eg:
>>> st="abcd"
>>> st.islower()
True
>>> st="abcd123"
>>> st.islower()
True
>>> st="ABCD"
>>> st.islower()
False
>>> st="1234"
>>> st.islower()
False
>>> st="abcdABCD"
>>> st.islower()
False
isupper():
Returns true if all characters in the string are in uppercase, otherwise returns
false.
eg:
>>> st="ABCD"
>>> st.isupper()
True
>>> st="abcd"
>>> st.isupper()
False
>>> st="ABCD123"
>>> st.isupper()
True
>>> st="abcdABCD"
>>> st.isupper()
False
>>> st="1234"
>>> st.isupper()
False
Sets
A set is a collection of values(elements)with no duplicate elements.
This is based on a data structure known as a hash table. Sets support
mathematical operations like union, intersection, difference, and symmetric
difference. Curly braces or the set() function can be used to create sets.
Syntax :
1)Set_name={item-1,item-2,..,item-n}
2)set_name = set([Sequence])
Eg:
>>> a={1,2,3,4,5}
>>> a
{1, 2, 3, 4, 5}
>>> b={1,2,3,1}
>>> b
{1, 2, 3}
>>> s=set([3,1,5,4])
>>> s
{1, 3, 4, 5}
Set1.py
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)
Output: {1, 2, 3, 4, 5, 6, 7, 8}
Syntax of Union Method:
union(Another set)
Eg:
>>> a={1,3,5,7,9}
>>> b={1,2,3,4,5}
>>> a.union(b)
{1, 2, 3, 4, 5, 7, 9}
>>> b.union(a)
{1, 2, 3, 4, 5, 7, 9}
>>> a={1,2,3,4,5}
>>> b={4,5,6,7,8}
>>> c={6,7,8,9}
>>> print(a|b|c)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
Set Intersection
Intersection of A and B is a set of elements that are common in both sets.
Intersection is performed using & operator. Same can be accomplished using the
method intersection() .
>>>A = {1, 2, 3, 4, 5}
>>>B = {4, 5, 6, 7, 8}
>>>print(A & B)
{4, 5}
Eg:
>>> A.intersection(B)
{4, 5}
Set Difference
Difference is performed using '-' operator. Same can be accomplished using the
method difference() .
Difference of A and B ( A - B ) is a set of elements that are only in A but not in B .
Similarly, B - A is a set of elements in B but not in A .
Eg:
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> print(A - B)
{1, 2, 3}
Eg:
>>> A.difference(B)
{1, 2, 3}
Eg:
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
2) clear
Remove all elements from a set
Syntax:
clear()
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.clear()
>>> A
set()
3) pop
Remove and return first set element.
Syntax:
pop()
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.pop()
1
>>> A
{2, 3, 4, 5}
5) remove
Remove an element from a set.
Syntax:
remove(element)
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.remove(3)
>>> A
{1, 2, 4, 5}
>>> A.remove(8)
KeyError: 8
Set_ope.py
a=set()
print("Enter First Set")
while True:
a.add(int(input()))
ch=input("Enter Anohter Element(y/n) :")
if(ch=='n'):
break
b=set()
print("Enter Second Set")
while True:
b.add(int(input()))
ch=input("Enter Anohter Element(y/n) :")
if(ch=='n'):
break
print("First set :",a)
print("Second set :",b)
print("Union of Two Sets :",a|b)
print("Intersection of Two Sets :",a&b)
print("Difference of Two Sets :",a-b)
print("Symmetric Difference :",a^b)
Built-in functions
1)len(set)
Returns the number of items in the set.
2)max(set)
Returns the maximum element in the set.
3)min(set)
Returns the minimum element in the set.
4) sum(set)
Returns the sum of items in the set.
5)sorted(set)
Return a new sorted list from elements in the set
Eg:
Set_fun.py
s=set()
print("Enter Elements")
while True:
s.add(int(input()))
ch=input(("Enter Anohter Element(y/n) :")
if(ch=='n'):
break
print('Given set is :',s)
print ('Length of set is :', len(s))
print ('Maximum value is :' , max(s))
print ('Minimum value is :' , min(s))
print ('Sum of items in set is :', sum(s))
Dictionaries
Python dictionary is an unordered collection of items. Creating a dictionary is placing
items inside curly braces {} separated by comma. An item has a key and the
corresponding value expressed as a pair. Each key is separated from its value by a
colon ( key : value ).
Syntax:
Dictionary_name = { key-1: value-1, key-2: value-2,….., key-n: value-n}
-
Eg1:
>>> d = {'a':10, 'b':1, 'c':22}
>>> d
{'a': 10, 'b': 1, 'c': 22}
Eg2:
>>> d = {'Name': 'Harsha', 'Age': 6, 'Class': 'First'}
>>> print (d['Name'])
Harsha
>>> print (d['Age'])
6
>>> print (d['Class'])
First
Updating Dictionary
Eg1:
>>> d = {'Name': 'Hari', 'Age': 7, 'Class': 'First'}
>>> d
{'Class': 'First', 'Name': 'Hari', 'Age': 7}
>>> d['Age'] = 8
>>> d['School'] = "ABC School"
>>> d
{'Class': 'First', 'Name': 'Hari', 'Age': 8, 'School': 'ABC School'}
1 len(dict)
Gives the total length of the dictionary.
2 str(dict)
Produces a string representation of a dictionary
1 clear()
Removes all elements of dictionary
2 items()
Returns a list of dict's (key, value) tuple pairs
3 keys()
Returns list of dictionary dict's keys
4 values()
Returns list of dictionary dict's values
Eg1:
>>> dict = {'a':10, 'b':20, 'c':30}
>>> dict
{'a': 10, 'b': 20, 'c': 30}
>>> len(dict)
3
>>> str(dict)
"{'b': 20, 'a': 10, 'c': 30}"
Eg2:
d = {'a':10, 'b':1, 'c':22}
>>> d.items()
dict_items([('a', 10), ('b', 1), ('c', 22)])
Eg3:
>>> dict.values()
dict_values([20, 10, 30])
>>> dict.items()
dict_items([('b', 20), ('a', 10), ('c', 30)])
>>> dict.keys()
dict_keys(['b', 'a', 'c'])
>>> dict.clear()
>>> dict
{}
Note:
Arrays
Arrays are fundamental part of most programming languages. It is
the collection of elements of a single data type. However, in Python,
there is no native array data structure. So, we use Python lists instead
of an array.
Functions and Modules
Function
A function is a group of statements that can be invoked any
number of times. Besides the built-in functions, you can define
our own functions. In Python, a function always returns a value.
Syntax:
def function-name( [parameter list] ):
statement(s)
Eg1:
To Find sum of two objects
Func1.py
def sum(x,y):
return x+y
Eg2:
To find maximum value of given two values
fun2.py
def maxval(x,y):
if x>y :
return x
else :
return y
def func_name(identifier-1,identifier-2=value,…) :
statements
Eg3:
Func3.py
def sum(x, y=20):
return x+y
print (sum(10))
print (sum(100,200))
Keyword Arguments
A value passed to a parameter by referring to its name is known as a
keyword argument.
Kwarg.py
def maxval(x,y=10,z=20):
if x>y and x>z :
return x
elif y>z :
return y
else :
return z
output:
Maximum value : 30
Maximum value : 20
Maximum value : 50
def compute():
global x
print ("Value of x in compute function is", x)
x=x+5
def dispvalue():
global x
print ("Value of x in dispvalue function is", x)
x=x-2
x=0
compute()
dispvalue()
compute()
print ("Value of x outside functions is", x)
output:
Value of x in compute function is 0
Value of x in dispvalue function is 5
Value of x in compute function is 3
Value of x outside functions is 8
Local_var.py
def compute(x):
x=x+5
print ("Value of x in function is", x)
x=10
compute(x)
print ("Value of x is still", x)
output:
Value of x in function is 15
Value of x is still 10
Lambda Function
A lambda function is an anonymous function.
The body of the lambda function is small, a single
expression.
def func(x) :
return x*2
n=func(3)
print(n)
output:
6
func=lambda x: x*2
n=func(3)
print(n)
output:
6
#To Display natural numbers from 1 to given number using user defined
function
ndisp.py
def display(x) :
for i in range(1,x+1):
print(i,end='\t')
#To calculate and Display factorial of given number using user defined
function
def factorial(x) :
f=1
while x>=1 :
f=f*x
x=x-1
return f
def reverse(x) :
rev=0
while x>0 :
rev=(rev*10)+(x%10)
x=x//10
return rev
n=int(input("Enter any Number :"))
r=reverse(n)
print("Reverse Number :",r)
def fibo(x) :
a,b,c=1,0,0
for i in range(x):
print(c,end="\t")
c=a+b
a=b
b=c
Function Attributes
In Python, functions are treated as objects, A function object
has a number of attributes that you can use to get more
information about a function.
A list of function attributes are shown in below Table
fun_att.py
Recursive function
a function calls itself is called as Recursive function.
A function calling itself will generate an infinite loop, so when
implementing recursion, an exit condition must be included in the
function.
Note :
Recursion is implemented with the help of a data structure known
as a stack
#To Display natural numbers from 1 to given number using recursive function
def display(x):
if x > 1:
display(x-1)
print(x,end='\t')
#To calculate and Display factorial of given number using recursive function
def fact(x) :
if x<=1 :
return 1;
else :
return x * fact(x-1)
Modules
A module is a file consisting of a few functions ,variables and classes
used for a particular task. A module can be imported in any program and
can be used it. The filename of the module must have .py extension.
Pre-defined Modules
Calendar module
It is used to display a calendar of a specified Year or Month.
Eg:
import calendar
prcal
It is a method and is used to display calendar of specified year
(default 3 months in a row)
Syntax:
prcal( year,m=3)
eg:
calendar.prcal(2018)
calendar.prcal(2018,m=2)
month
It is a method and is used to display calendar of specified year and
month
Syntax:
month(year,month)
Eg:
print(calendar.month(2018,3))
eg:
>>> from calendar import prcal
>>> prcal(2018)
cal1.py
import calendar
year = int(input("Enter Year :"))
calendar.prcal(year)
cal2.py
import calendar
year = int(input("Enter Year :"))
month = int(input("Enter month :"))
print(calendar.month(year,month))
time module
ctime :
It is a method and is used to display current date and time
Eg:
import time
time.ctime()
o/p: 'Fri Apr 26 10:47:19 2019'
math Module
mth.py
import math
print("pi = ",math.pi)
print("pi = ",round(math.pi,2))
print("Ceil value of 7.3:",math.ceil(7.3))
print("Floor value of 7.3 :",math.floor(7.3))
print("Square root of 9:",math.sqrt(9))
print("pow of 2 and 3 :",math.pow(2,3))
eval
Returns a result of the evaluation of a Python expression.
Syntax
eval (expression)
eg:
>>> x = 1
>>> eval('x+1')
2
>>> eval('2*2')
4
random module
Example:
from random import choice
choice([2,4,6,8,10])
You will get a random value picked from the specified sequence, which
may be 2, 6, or some other value from the list.
rand1.py
from random import choice
k=choice([2,4,6,8,10])
print ("Random number is",k)
Output:
Random number is 4
rand2.py
from random import choice
ch='y'
while ch=='y' :
k=choice(range(1,10))
print ("Random number is ",k)
ch=input("Do you want to Continue(y/n) :")
eg:
exit
It is method belongs to sys module, it terminates the program.
Syntax:
sys.exit()
mymodule.py
def wel() :
print("Welcome to Python Modules")
x=10
y=20
Command-line Arguments
Command-line arguments are used to pass arguments to a program
while running it. Each command line argument that you
pass to the program will be stored in the sys.argv variable.
(sys is a module).
The sys.argv is a list that always has a length of at least 1, the item at
index 0 is the name of the Python program you are running.
commandline1.py
import sys
print ('There are %d arguments' % len(sys.argv))
print ('The command line arguments are:' )
print (sys.argv)
for i in sys.argv:
print(i)
Object Oriented Programming
Object oriented programming introduced in 1980’s by
Bjarne Stroustrup. OOP'S improves the style of a program. It allows the
user to develop a program structure. This concept mainly introduces a
mechanism called class.
1. Objects
2. Classes
3. Data encapsulation and Data abstraction
4. Inheritance
5. Polymorphism
Objects :
Objects are the runtime entities in object oriented programming. They
may represents a person, a place, etc. that are program has to handle.
They may also represent user defined data.
Classes :
The objects contain data and code to manipulate that data, the entire set
of data and code of an object can be made a user defined data type such
as class. Once a class has been defined, we can create any number of
objects belongs to that class.
Data abstraction:
abstact data type: a set of operations performed on a particular data
type is known as abstract data type.
The technique of creating new abstract data types that are well suited to
an application is known as data abstraction.
Data abstraction means we can combine the data structures and
operations on the data structures together into a new abstract data type.
An abstract data type not a part of language definition, they are created
by the user.
Inheritance :
It is a mechanism which is used to extend the definition of existing
class. The extension can be done by declaring some other class. The class
that is originally present is called as Base/super class and the class which is
extended with the help of inheritance is called as Derived/sub class. A
derived class always can access the members of base class, whereas a
base class never access the members of derived class. The main purpose
of inheritance is reusability of definition that is already made.
Polymorphism :
The word polymorphism is derived from 2 latin Words
1. Poly (many)
2. Morphs (forms)
Polymorphism is nothing but the ability to access different
implementations of the function using the same name.
There are 2 levels at which polymorphism operates.
1. Compile time polymorphism
2. Run time polymorphism
Syntax:
class classname[ (base classes) ] :
statements
where classname is an identifier that is bound to the class object. You can create
either an independent class or inherits from other classes.
class variable(s)
2. Instance variable:
The variables that are defined inside a method are known as instance
variables. Changes made to instance variables by any instance are limited
to that particular instance and don’t affect other instances.
Instances(objects)
A class is a template or blueprint of data and operations.To
use the data and operations, you need to create instances. An
instance is a variable of a class. You can create as many
instances of a class and each instance gets a separate copy of the
methods and attributes defined in the class(except class
variables, class methods). Each instance can access the methods
and attributes of the class independently.
ob1=num()
ob2=num()
print("Initial value in the class valriable :",num.n);
print("Initial value in the First Object :",ob1.n)
print("Initial value in the Second Object :",ob2.n)
num.n=100
print(" value in the classvalriable :",num.n);
print("value in the First Object :",ob1.n)
print("value in the Second Object :",ob2.n)
def datainput(self):
self.n=int(input())
def output(self) :
print(self.n)
ob1=num()
ob2=num()
print("Enter the value into First Object :",end='')
ob1.datainput()
print("Enter the value into Second Object :",end='')
ob2.datainput()
rectar1.py
class rect:
def __init__(self):
self.l = 8
self.b = 5
def rectarea(self):
return self.l * self.b
r=rect()
print ("Area of rectangle is ", r.rectarea())
class rect:
def __init__(self, x,y):
self.l = x
self.b = y
def rectarea(self):
return self.l * self.b
r=rect()
s=rect(10,20)
print ("Area of rectangle is ", r.rectarea())
print ("Area of rectangle is ", s.rectarea())
__del__ Method
------------------
It is Called when the instance is to be destroyed.
This is also called as destructor.
del statement
del is a statement and is used to delete (destroyed) specified object.
Syntax:
del object_name
destructor.py
class test:
def __init__(self):
print("Instace (object) is Created")
def __del__(self):
print ("Instace (object) is destroyed")
t=test()
del t
Publicaccess.py
class rect:
def __init__(self, x,y):
self.l = x
self.b = y
def rectarea(self):
return self.l * self.b
r=rect(5,8)
print ("Area of rectangle is ", r.rectarea())
print ("Area of rectangle is ", r.l* r.b)
def rectarea(self):
return self.__l * self.__b
r=rect(5,8)
print ("Area of First rectangle is ", r.rectarea())
s=rect(10,20)
'''
print ("Area of Second rectangle is ", s.__l* s.__b)
It is not possible,Because l abd b are private members
'''
print ("Area of rectangle is ", s.rectarea())
Class Methods
A class method has no self argument and receives a class(cls) as its first
argument. The class method can also be called directly through the class
name without instance. A class method is defined using the
' @classmethod ' decorator.
Syntax:
@classmethod
def method_name(cls,[arg-list]) :
statements
classmethod.py
class book:
price=100
@classmethod
def display(cls):
print (cls.price)
def show(self,x):
self.price=x
print (self.price)
book.display()
# book.show(200) It is not working ,because it not class method
b=book()
b.show(200)
Static Methods
A static method is an ordinary function that is built using the
@staticmethod decorator . The difference between a static method and a
class method is that a static method has no cls argument. This method can
also be called directly through the class name without instance.
Syntax:
@staticmethod
def method_name([arg-list]) :
statements
staticmethod.py
class book:
price=100
@staticmethod
def display():
print (book.price)
book.display()
Garbage Collection
Garbage collection is a procedure of freeing up the memory. The
memory that is used by the instances are usually freed up automatically .
That’s why memory leaks are rare in Python.
stu_cl.py
class student :
def datainput(self) :
self.sno=int(input("Enter Student Number :"))
self.sname=input("Enter Student Name :")
print("Enter Marks in C,C++,Java and Python ")
self.c=int(input())
self.cpp=int(input())
self.java=int(input())
self.python=int(input())
def calculate_result(self) :
self.tot=self.c+self.cpp+self.java+self.python
self.avg=self.tot/4
if self.c>=50 and self.cpp>=50 and self.java>=50 and self.python>=50
:
self.result='Pass'
if self.avg >=90 :
self.grade='A+'
elif self.avg>=70 :
self.grade='A'
else :
self.grade='B'
else :
self.result='Fail'
self.grade='No Grade'
def printresult(self) :
print(" RESULT ")
print("------------------------------------")
print("Sudent Number :",self.sno)
print("Sudent Name :",self.sname)
print("Marks in C :",self.c)
print("Marks in C++ :",self.cpp)
print("Marks in Java :",self.java)
print("Marks in python :",self.python)
print("Total Marks in :",self.tot)
print("Average : %.2f" %(self.avg))
print("Result :",self.result)
print("Grade :",self.grade)
print("-------------------------------------")
s=student()
s.datainput()
s.calculate_result()
s.printresult()
Inheritance
It is a mechanism which is used to extend the definition of an existing
class. The extension can be done by declaring some other class. The class,
that is originally present is called as “super class” or "Base class" and the
class which is extended with the help of inheritance is called “sub class” or
derived class . A sub class always access the members of super class,
whereas the super class never access the members of sub class. The main
purpose of inheritance is the reusability of definition that are already made.
Types of Inheritance
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
Single Inheritance
This is the simplest type of inheritance, where one class is derived from
another single class.
inr1.py
class base :
def __init__(self):
self.n=100
def display(self):
print("Initial value :",self.n)
class derv(base):
pass
d=derv()
d.display()
inr11.py
class base :
def accept(self):
self.n=int(input("Ennter any Number into base member :"))
def display(self):
print("Given value in the base member :",self.n)
class derv(base):
def datainput(self):
self.m=int(input("Enter the value into derv memeber :"))
def dataoutput(self):
d=derv()
d.accept()
d.datainput()
d.display()
d.dataoutput()
Method Overriding
If methods are defined with the same name both in base class and
derived classes, a derived class object always gives preference to the
derived class methods by overlooking base class methods. Hence it is
called overriding .
Invoking the overriding methods by the following way :
class_name . method_name([arg_list])
Note : This Syntax works only inside methods of derived class
inr2.py
class base :
def __init__(self):
self.n=100
def display(self):
print("Initial value in Base member :",self.n)
class derv(base):
def __init__(self):
base.__init__(self)
self.m=200
def display(self):
base.display(self)
print("Initial value in derv member :",self.m)
d=derv()
d.display()
inr22.py
class base :
def accept(self):
self.n=int(input("Ennter any Number into base member :"))
def display(self):
print("Given value in the base member :",self.n)
class derv(base):
def accept(self):
base.accept(self)
self.m=int(input("Enter the value into derv memeber :"))
def display(self):
base.display(self)
print(" Given value in the derv member :",self.m)
d=derv()
d.accept()
d.display()
Multilevel Inheritance
The mechanism of deriving a class from another derived class is called as
multi level inheritance.
inr3.py
class base :
def __init__(self):
self.a=100
def display(self):
print("Initial value in Base member :",self.a)
return None
class derv1(base):
def __init__(self):
base.__init__(self)
self.b=200
def display(self):
base.display(self)
print("Initial value in derv1 member :",self.b)
return None
class derv2(derv1):
def __init__(self):
derv1.__init__(self)
self.c=300
def display(self):
derv1.display(self)
print("Initial value in derv2 member :",self.c)
return None
d=derv2()
d.display()
Multiple Inheritance
Inr44.py
class base1 :
def __init__(self):
self.a=100
def display(self):
print("Initial value in Base1 member :",self.a)
class base2 :
def __init__(self):
self.b=200
def display(self):
print("Initial value in Base2 member :",self.b)
class derv(base1,base2):
def __init__(self):
base1.__init__(self)
base2.__init__(self)
self.c=300
def display(self):
base1.display(self)
base2.display(self)
print("Initial value in derv member :",self.c)
d=derv()
d.display()
inr4.py
class student:
def accept(self):
print("Enter Student Number :",end='');
self.sno=int(input())
print("Enter Student Name :",end='');
self.sname=input()
def display(self):
print("Sudent Number :",self.sno)
print("Sudent Name :",self.sname)
class marks :
def accept(self):
print("Enter Marks in C,C++ and Java ");
self.c=int(input())
self.cpp=int(input())
self.java=int(input())
def display(self):
print("Marks in C :",self.c)
print("Marks in C++ :",self.cpp)
print("Marks in Java :",self.java)
s=result()
s.cal_result()
s.display()
Hierarchical Inheritance
One class may be inherited by more than one class. This process is called as
hierarchical inheritance. i.e. one base class with several derived classes.
Inr45.py
class base :
def __init__(self):
self.a=100
def display(self):
print("Initial value in Base member :",self.a)
class derv1(base) :
def __init__(self):
base.__init__(self)
self.b=200
def display(self):
base.display(self)
print("Initial value in derv1 member :",self.b)
class derv2(base):
def __init__(self):
base.__init__(self)
self.c=300
def display(self):
base.display(self)
print("Initial value in derv2 member :",self.c)
d1=derv1()
d2=derv2()
d1.display()
d2.display()
File Handling
In Python a file is a container for a sequence of data objects,
represented as sequences of bytes. File handling is a technique
by which you can store data and can retrieve it later.
When you run a program, the processed data is displayed on
the screen and temporally stored in RAM, so if later you want to
see the data, you can’t get it. To overcome these problems we
use files.
Text files :
These are used for reading and writing data in the form of characters.
Binary files :
These are used for reading and writing data in the form of data blocks.
The following three steps are required for working with files:
1. Opening a file
2. Performing actions on the file (reading, writing, updating contents)
3. Closing the file
Opening a File
open()
It is a function and it opens a file
Syntax:
open(filename, mode)
‘filename’ represents the name of the file, and ‘mode’ specifies the
purpose for opening the file. The open() function returns a file handler that
represents the file on the disk drive.
File modes
Note :
To open a Binary file append ‘b’ to the mode string
Eg: ‘wb’,’rb’,etc.
readlines() : Read all lines from the file and returns a list
location :
0 - beginning of the file.
1 - current position.
2 - end of the file.
Textfile Operations
f = open('pyt.txt', 'w')
f.write(matter)
f.close()
f = open('pyt.txt','r')
lines = f.read()
print (lines)
f.close()
Reading line by line Data from a File
File2.py
f = open('pyt.txt','r')
while True:
line = f.readline()
if len(line) == 0:
break
print (line)
File Attributes
mode : This attribute is the mode of the file that was used`
to create the file object through the open() function.
File_att.py
f = open("a.txt", "r")
print ("Name of the file:", f.name)
print ("Opening mode:", f.mode)
print ("Closed? :", f.closed)
f.close()
print ("Closed? :", f.closed)
write a python script to open a text file , store data into file from
key board, read data from that file and display
file3.py
f = open('text.txt', 'a')
print("Enter text data into file 'end ' to stop")
while True :
st=input()
if(st=='end'):
break
f.write(st+'\n')
f.close()
f = open('text.txt','r')
lines = f.read()
print (lines)
f.close()
sleep
It is Method belongs time module, it delays flow of execution up to
Specified no of seconds.
sleep(seconds)
write a python script to enter any file name and display all
content in the given file
file4.py
import time
name=input("Enter any file name :");
f = open(name,'r')
while True :
ch = f.read(1)
if len(ch) ==0 :
break
print (ch,end='')
time.sleep(.10)
f.close()
Example program for seek method :
File5.py
f = open('h.txt', 'a+')
print("Enter text data into file 'end ' to stop")
while True :
st=input()
if(st=='end'):
break
f.write(st+'\n')
f.seek(0,0)
print("\nReading data from file")
lines = f.read()
print (lines)
f.close()
filecopy.py
f1 = open('a.txt', 'r')
lines = f1.read()
f1.close()
f2 = open('b.txt', 'w' )
f2.write(lines)
f2.close()
print("Fileis copied successfully")
print("Copied contents in the second file");
f2 = open('b.txt', 'r' )
lines = f2.read()
print (lines)
f2.close()
f = open('a.txt','r')
lines = f.readlines()
print('Original content of the file:')
for ln in lines:
print(ln,end='')
f.close()
del lines[1:3]
f = open('a.txt', 'w' )
f.writelines(lines)
f.close()
print('\nThe content of the file after deleting second and third line:')
f = open('a.txt', 'r' )
lines = f.read()
print (lines)
f.close()
codes : utf-8,ascii,etc.
utf-8 : utf stands for Unicode Transformation Format. The '8' means it uses 8-bit
blocks to represent a character.
binaryfile1.py
st = 'welcome to Python Binary files'
f = open("h.bin","wb" )
f.write(st.encode('utf-8'))
f.close()
f = open("h.bin","rb" )
fcontent=f.read()
f.close()
print('The content in the file ')
print (fcontent.decode('utf-8'))
Serialization (Pickling)
Serialization (also known as pickling) is a process of converting
structured (list, tuple, class, etc.) data into data stream format.
Serialization is done when storing data, and deserialization is done when
retrieving data. For pickling, you can use the module ‘pickle’ .
dump(obj, file)
This method belongs to pickle module, and is used to Write object
to a file.
load(file)
This method belongs to pickle module, and is used to read object
from a file.
bfile1.py
import pickle
class num:
def __init__(self, x):
self.n = x
def display(self):
print("Given Number :", self.n)
ob=num(100)
f = open('num.bin', 'wb')
pickle.dump(ob, f)
f.close()
del ob
f = open('num.bin','rb')
obj = pickle.load(f)
obj.display()
bfile2.py
import pickle
class student:
def datainput(self) :
self.id = int(input("Enter Student Id :"))
self.name = input("Enter Student Name :")
self.emailadd=input("Enter Email Eddress :")
def display(self):
print("Student ID:", self.id)
print("Studentr Name:", self.name)
print('Email Address:', self.emailadd)
f = open("stu.bin", "wb")
ob=student()
while True:
ob.datainput()
pickle.dump(ob,f)
ch=input("Do you wanto to Continue(y/n) :")
if ch=='n' or ch=='N' :
break
f.close()
print('\nInformation of the Students')
f = open("stu.bin","rb")
while True:
try :
obj = pickle.load(f)
except EOFError:
break
else:
obj.display()
print()
f.close()
Exception Handling
Exception is an error state, it occurs during the execution of an
instruction in a program. when an exception occurs it is possible to raise an
exception and when an exception is raised a set of instructions will be
executed and these instructions are referred as exception handler. When
an exception occurs, Python usually displays a technical message.
Syntax errors are different from exceptions, if syntax errors occur when
any statement doesn’t match the grammar of the Python interpreter.
To handle exceptions, you write the code in a block that begins with the
word try. There are two kinds of try blocks
1) try/except
2) try/finally
try/except:
The code written in the try block, and all the exceptions are handled
through the except clause. If you specify exception type, the except clause
can handle a single specified exception. If you don’t specify any exception,
except will handle all exceptions that appear in the code written in the try
block.
Syntax:
try:
statement(s)
except [SomeException]:
code for handling exception
[else:
statement(s)]
Exception Description
1. EOFError : Raised when you try to read beyond the
end of a file.
2. FloatingPointError : Raised when a floating-point operation
fails.
3. IOError : Raised when an I/O operation fails.
4. IndexError : Raised when you use an index value that is
out of range.
Etc.
Exp1.py
try:
print("Enter any two Numbers ")
a=int(input())
b=int(input())
c=a/b
print("Division :",c);
except ZeroDivisionError:
print ('Division Error' )
exp2.py
import sys
try:
name = input('Enter your name : ')
print ('Given name :', name)
except :
print ('EOF error has occurred' )
exp3.py
try:
d=m/n
print ('Division :',round(d,2))
except TypeError:
print ('You have not entered a numeric value")
except ZeroDivisionError:
print ('You have entered zero value, Division is Not possible")
Nested try
exp33.py
m = input('Enter First number : ')
n = input('Enter Second number : ')
try :
m=int(m)
n=int(n)
try:
d=m/n
print ('Division :',round(d,2))
except ZeroDivisionError:
print ("You have entered zero value, Division is Not possible")
except :
print ("You have not entered numeric values")
try/finally:
The code written in the finally block always executes whether an
exception occurs or not.
exp4.py
try:
f = open("a.txt", "r")
try:
lines = f.read()
print (lines)
finally:
f.close()
except IOError:
print ('File does not exist')
Raising an Exception
Exceptions are automatically raised when some undesired situation occurs
during program execution. You can raise an exception explicitly through
the ‘raise’ statement in a ‘ try/except ‘ block.
Syntax:
raise ExceptionType
exp5.py
try:
print("Enter any two Numbers ")
a=int(input())
b=int(input())
if b==0 :
raise ZeroDivisionError
c=a/b
print("Division :",round(c,2));
except ZeroDivisionError:
print ('Division Error' )
exp6.py
class myException(Exception):
def __init__(self,st):
self.mesg = st
def getmessage(self):
return self.mesg
try:
print("Enter any two Numbers ")
a=int(input())
b=int(input())
if b==0 :
raise myException("Division Error")
c=a/b
print("Division :",round(c,2))
except EOFError:
print ('You pressed EOF ')
except myException as me:
print (me.getmessage())
else:
print ('No Exceptions')
abs(x) :
Return the absolute value of a number.
bin(x) :
Convert an integer number to a binary string prefixed with “0b”.
hex(x) :
Convert an integer number to a lowercase hexadecimal string
prefixed with “0x”.
oct(x) :
Convert an integer number to an octal string prefixed with “0o”.
num_sys.py
n=int(input("Enter any Number :"))
print("Absolute value of given Number :",abs(n))
print("Binary value of given Number :",bin(n))
print("Octal value of given Number :",oct(n))
print("Hexadecimal value of given Number :",hex(n))
Eg:
Conversion binary,oct and hexdecimal to integer.
int('0b100',2) = 4
int('0o644',8) = 420
int ('0x1a4',16)=420
help
It displays help content of specified object.
Syntax:
help(object)
eg:
>>> help(str)
Turtle graphics
Turtle graphics is a popular for introducing programming to kids. It was
part of the original Logo programming language. Imagine a robotic turtle
starting at (0, 0) in the x-y plane.
turtle:
The turtle module is an extended reimplementation of Python standard
distribution up to version Python 2.5.
Turtle methods
Move and draw
forward() | fd()
backward() | bk() | back()
right() | rt()
left() | lt()
goto() | setpos() | setposition()
home()
circle()
setx()`
sety()
screensize() | setup()
Tell Turtle’s state
position() | pos()
xcor()
ycor()
Color control
color()
pencolor()
fillcolor()
Filling
begin_fill()
end_fill()
Turtle state Visibility
showturtle() | st()
hideturtle() | ht()
etc.
tg1.py
from turtle import *
for i in range(4):
forward(50)
right(90)
tg2.py
from turtle import *
for i in range(5):
forward(200)
right(144)
done()
tg3.py
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
tg4.py
done()
Tkinter Programming
Tkinter is the standard GUI library for Python. Tkinter provides a fast and
easy way to create GUI applications.
Tk()
geometry()
Syntax:
geometry("Width x Height")
eg: geometry("300x200")
title()
Syn:
title(str)
mainloop()
gui1.py
import tkinter
top = tkinter.Tk()
top.title("Python GUI");
top.geometry ("300x100")
top.mainloop()
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes
used in a GUI application. These controls are commonly called widgets.
1.Button :
Syntax
Parameters
· master − It represents the parent window.
Options :
text : display text on the Button
is clicked.
font,image,height,width,etc.
pack()
messagebox
showinfo():
syntax:
showinfo(windowtitle,message)
gui2.py
top = Tk()
top.geometry("300x100")
def func():
B.pack()
top.mainloop()
2.Canvas
The Canvas is a rectangular area for drawing pictures or other layouts.
You can place text, widgets or frames on a Canvas.
Syntax:
Parameters
options − Here is the list of most commonly used options for this widget.
options:
width,height,etc.
fileobject=PhotoImage(file = "image.gif")
gui3.py
import tkinter
top = tkinter.Tk()
C.pack()
top.mainloop()
3.Checkbutton
Syntax
options: width,height,onvalue,offvalue,etc.
gui4.py
top = Tk()
height=5,width = 20)
height=5,width = 20)
C1.pack()
C2.pack()
top.mainloop()
4.Label
This widget implements a display box where you can place text or images.
Syntax
5. Entry
Syntax
Entry( master, option, ... )
Gui5.py
top = Tk()
E = Entry(top)
E.pack(side = RIGHT)
top.mainloop()
6.Frame
The Frame widget is very important for the process of grouping and
organizing other widgets . It works like a container, which is responsible
for arranging the position of other widgets.
Syntax
Gui6.py
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
root.mainloop()
7.Listbox
The Listbox widget is used to display a list of items from which a user can
select items.
syntax
Listbox ( master, option, ... )
insert :
insert(index,item)
gui7.py
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(0, "Python")
Lb1.insert(1,"C")
Lb1.insert(2,"C++")
Lb1.insert(3,"Java")
Lb1.pack()
top.mainloop()
8.Menu
Methods
add_command (options) :
options :label,command,etc.
add_cascade(options):
add_separator() :
config()
Gui8.py
from tkinter import *
def donothing():
messagebox.showinfo("GUI","WELCOME TO PYTHON
MENUS")
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar,tearoff=0)
filemenu.add_command(label="New",
command=donothing)
filemenu.add_command(label="Open",
command=donothing)
filemenu.add_command(label="Save",
command=donothing)
filemenu.add_command(label="Save as...",
command=donothing)
filemenu.add_command(label="Close",
command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit",
command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu.add_command(label="Undo",
command=donothing)
editmenu.add_separator()
editmenu.add_command(label="Cut",
command=donothing)
editmenu.add_command(label="Copy",
command=donothing)
editmenu.add_command(label="Paste",
command=donothing)
editmenu.add_command(label="Delete",
command=donothing)
editmenu.add_command(label="Select All",
command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu.add_command(label="Help Index",
command=donothing)
helpmenu.add_command(label="About...",
command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
root.config(menu=menubar)
root.mainloop()
9.Toplevel
Syntax
Gui9.py
from tkinter import *
top = Tk()
top.geometry("300x100")
def func():
ob=Toplevel()
ob.title("MYWINDOW")
top.mainloop()
Database Handling
Sometimes you need to save data entered by the user for
future use. There are two ways to save data that is supplied by the
user while running an application. The first way is to use file
handling. The second way is to use a database management
system.
To interface with a database using Python, you need the Python
database API, which supports a wide range of database servers,
such as MySQL, Microsoft SQL Server , Oracle , Etc. You need to
download a separate database API module for each database you
want to access. Here we want to access MySQL Database Server
through Python.
Why MySQL?
MySQL is one of the most popular relational database management
systems . It’s open-source software, secure, fast, and very easy to
learn.
MYSQL COMMANDS-1
1.Create a database on the mysql server :
create database database_name ;
3.Switch to a database :
use database_name ;
connect:
It is a method belongs to pymysql/MYSQLdb module and it
connects the mysql database server and returns connection object.
Syntax:
connect(host, user, passwd, db)
close:
It is a method belongs to connection object and it closes the
database connection.
Syntax:
connection_object.close()
db1.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="harshith",db="mydb")
print("Connected to Database")
except :
print("Unable to Commect database")
conn.close()
MYSQL COMMANDS-2
1.Create table :
Syntax:
Create table table_name (columnName-1 datatype,…….,columnName-n datatype);
Eg:
create table emp (eno int,ename char(20), salary float);
5. To Delete a table :
drop table table_name;
cursor()
This Method belongs to connection object ,it creates a cursor object.
Using this cursor object we can execute sql statements.
execute():
this Methos Belongs to cursor object and it executes sql statements;
syntax:
cusorobject. execute(sql statement)
db2.py
import pymysql
try:
conn=pymysql.connect (host="localhost",user="root",passwd="harshith",db="mydb")
cursor=conn.cursor()
cursor.execute (''' create table emp (eno int,ename char(20), salary float) ''')
print("Table is Created")
cursor.close()
conn.close()
except :
print ("Unable to create Table")
eg:
insert into emp values(100,'abc',5000.00)
commit():
This method belongs to connection object.To apply the modifications to
the database table, use the commit() method.
Once commit() is executed, then it’s not possible to undo the changes.
Db3.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="harshith",db="mydb")
cursor=conn.cursor()
cursor.execute (''' insert into emp(eno,ename,salary)
values (200, 'xyz', 25000.00) ''')
print("One Row Inserted")
cursor.close()
conn.commit()
conn.close()
except :
print ("Unable to insert Row")
rollback():
The rollback() method cancels all the modifications applied to the
database table. It keeps the database table when it was last saved.
db4.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="harshith",db="mydb")
cursor=conn.cursor()
while True:
eno=int(input("Enter Eno :"))
ename=input("Enter Ename :")
salary=float(input("Enter Salary :"))
try:
cursor.execute (''' insert into emp(eno,ename,salary) values (%d, '%s', %f) '''
%(eno,ename,salary))
print("One Row Inserted")
conn.commit()
except:
conn.rollback()
ch=input("do you want to insert Another Record (y/n) :")
if ch=='n' or ch=='N' :
break;
cursor.close()
conn.close()
except :
print ("Unable to insert Row")
conn=pymysql.connect(host="localhost",user="root",passwd="hars
hith",db="mydb")
cursor=conn.cursor()
try:
cursor.execute ("SELECT * from emp")
print ("ENO\t\tENAME\t\tSALARY")
print("----------------------------------------------------------")
while(1):
row=cursor.fetchone()
if row==None:
break
print ("%d\t\t%s\t\t%.2f" %(row[0], row[1], row[2]))
except :
print ("Error in fetching rows")
cursor.close()
conn.close()
except :
print ("Unable to connect database")
db6.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="harshith",d
b="mydb")
cursor=conn.cursor()
try:
cursor.execute ("select * from emp")
print("----------------------------------------------------------")
print ("ENO\t\tENAME\t\tSALARY")
print("----------------------------------------------------------")
rows=cursor.fetchall()
for row in rows:
print("%d\t\t%s\t\t%.2f" %(row[0], row[1], row[2]))
except :
print ("Error in fetching rows")
print("----------------------------------------------------------")
cursor.close()
conn.close()
except :
print ("Unable to connect database")