PYT
PYT
PYT
Introduction
Python is a very powerful high-level,general-purpose, object-oriented
programming language created by Guido van Rossum in 1989.
Features of Python
Python is easy to learn.
It has easier to read syntax.
Python is free.
It comes with a large number of libraries.
Python can be integrated with other languages,
like C, C++, and Java.
Python is a good choice for web development.
Efficient memory management.
Python supports exception handling.
Interacting with Python
There are two ways to work with Python :
Using Command Line Mode
Using IDLE mode
2) Spider
Spyder is an open-source, cross-platform IDE developed by Pierre Raybaut in 2009.
It is integrated with many of the scientific Python libraries namely Scipy, NumPy, Matplotlib,
Pandas etc.
3) PyDev
is basically an open-source third-party package which serves as a plug-in for Eclipse to
enable it for Python development.
4) Rodeo
Rodeo is an open source Python IDE developed by Yhat. It is built in particular
for machine learning and data science.
5) Sublime Text
Sublime-Text is a cross-platform IDE developed in C++ and Python. In addition to Python,
it provides support for other languages as well
6) Wing
This IDE was created by Wingware. It is a lightweight IDE designed to allow
quick programming.
7) EricPython
Eric is written in Python and is free software. Its source code is available freely and can
-be studied and recreated by anybody.
8) Atom
Atom is an open source free IDE built using web technologies. Atom is based on the
Electron framework which is built by GitHub which in turn is written in CoffeeScript and
Less.
9) Thonny
Thonny is an IDE developed for beginners. It provides step-by-step assistance to the
programmer.
10)IDLE
completely in Python and it comes as a default implementation along with Python IDLE
is written
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 3rd 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.11 This number can vary in different versions of Python.
Note: 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
–2147483648 to 2147483647
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 (or) triple quotes. By using triple quotes
we can write multi-line strings.
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.
Eg. valid invalid
m 1m
_m m$
num1 else
tot_sal tot sal
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.
a=5
print('The value of a is', a)
Output: The value of a is 5
print(1,2,3,4,5)
Output: 1 2 3 4 5
print(1,2,3,4,5,sep='*')
Output: 1*2*3*4*5
print(1,2,3,4,5,sep='#',end='$')
Output: 1#2#3#4#5$
Eg:23
print('WEL'+'COME')
output: WELCOME
It display the two strings on the same line without any space in
between the two strings.
Formatting the Output
Sometimes we would like to format our output . This can be done by
using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
Output :The value of x is 5 and y is 10
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
Comments:
Comments lines are for documentation purposes and
these lines are ignored by the interpreter.
# - Single line comment
’’’
---------------------
--------------------- Multi line comment
----------------------
’’’
Literals in Python
Generally, literals are a notation for representing a fixed value in source
code. They can also be defined as raw value or data given in variables or
constants.
Python has different types of literals.
1.String literals
2.Numeric literals
3.Boolean literals
4.Literal Collections
5.Special literals
String literals
A string literal can be created by writing a text(a group of Characters )
surrounded by the single(' '), double(“”), or triple quotes. By using triple
quotes we can write multi-line strings.
Examples:
s = 'WELCOME'
t = "Welcome To Python"
m = '''Hello
Welcome To
Python Programming'''
Numeric literals
They are immutable and there are three types of numeric literal
1.Integer
2.Float
3.Complex.
Examples:
n=100
f=14.219
c=(2+3j)
Boolean literals
There are only two Boolean literals in Python. They are True and False.
x=True
k=x+4 (1+4=5)
Literal Collections
1.List literals
2.Tuple literals
3.Set literals
4.Dict literals
Examples
# List literals
numbers = [1, 2, 3, 4, 5]
# Tuple literals
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
# Set literals
vowels = {'a', 'e', 'i', 'o', 'u'}
# Dict literals
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
Special literals
Python contains one special literal (None). ‘None’ is used to define a null
variable.
Example
ob=None
P1.py
eno = 100 # An integer assignment
ename = "HHHH" # A string assignment
salary = 20000.00 # A floating point assignment
print("Employ Number :",eno)
print("Employ Name :", ename)
print("Salary :",salary)
Format strings
We can use format strings in print() function like printf() style used
in ‘C’ language.
The list of format Strings
eg1:
C Language
int n=10;
printf("value of n = %d",n);
python
n=10
print("value of n = %d"%n)
eg2:
>>> m=10;n=20
prg: Emp.py
eno=100
ename='HHHH'
grade='A'
salary=20000.00
print ("Employ Number :%d"%eno)
print ("Employ Name :%s"%ename)
print ("Grade :%c"%grade)
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])
where prompt is the string we wish to display on the screen. It is
an optional.
2) int(x)
This function converts string type to integer.
Program
Conv1.py
3. ord(x) :
converts a character to integer(Unicode value).
4.chr(x) :
Converts an integer(Unicode value) to a character
5. str(x) :
Converts integer (or) float into a string.
6.complex(real,imag) :
Converts real numbers to complex number
Eg(Unicode values):
A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57
Esc 27
Backspace 8
Enter 13
SpaceBar 32
Tab 9
etc.
program
Conv2.py
c = ord('A')
print ("After converting character to integer :",c)
c = chr(65)
print ("After converting integer to character :",c)
c = str(123)
print ("After converting integer to string :",c)
c = complex(1,2)
print ("After converting integers to complex number :",c)
Python Indentation
Most of the programming languages like C, C++and Java use curly
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.
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 AND
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
+=
-=
*=
/=
//=
%=
**=
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,set,Etc.).
>>> st='abcd'
>>> 'a' in st
True
>>> 'k' not in st
True
>>> x='a'
>>> x in st
True
>>> "WEL" in "WELCOME"
True
>>> "WCE" in "WELCOME"
False
if condition :
block
2. if-else statement
It is an extension of simple if statement.
if condition :
if block
else :
else block
The condition is a Boolean expression, if it is true then if block will be
executed otherwise else block will be executed.
if a> b :
max=a
else :
max=b
print("Maximum value :",max)
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
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
quit.
break.py
To display Numbers from 1 to given number,if the given
number is greater than 20 it displays only 1 to 20 using
break.
program
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 5 6 8 9 10
pass.py
k=1
while k <=10 :
if k==4 or k==7:
pass
else:
print (k,end='\t')
k+=1
Output:
1 2 3 5 6 8 9 10
Nested loops
Using a loop statement within another loop is called as
nested loops.
if count==2 :
print(i,"\t",end='')
patteren1
n=5
*****
*****
*****
*****
*****
patteren2
n=5
*
**
***
****
*****
patteren3
n=5
1
22
333
4444
55555
patteren4:
n=5
1
12
123
1234
12345
patteren5
n=5
*
* *
* * *
* * * *
* * * * *
patteren6
n=5
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
n = int(input("Enter the value of n : "))
s=n*2
k=1
for i in range(1,2*n) :
print("%*c"%(s,32),end='')
for j in range(1,k+1):
print('*',end=' ')
print()
if i<n :
s=s-2
k=k+1
else :
s=s+2
k=k-1
n=5
1
121
12321
1234321
123454321
1
212
32123
4321234
543212345
Data Structures
1)Sequences
A sequence is a collection objects . You can identify an object
in a sequence by its index.
Examples of sequences: lists, tuples, and strings.
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 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]
>>> print(a[2])
T
>>> print(a[5])
N
Sub lists
>>> a=[[1,2,3],[100,200,300]]
>>> a
[[1, 2, 3], [100, 200, 300]]
>>> a[0]
[1, 2, 3]
>>> a[1]
[100, 200, 300]
>>> print(a[0][1])
2
>>> print(a[1][2])
300
>>> a=[[100,"BDPS"],[1,2,10.35,True]]
>>> a
[[100, 'BDPS'], [1, 2, 10.35, True]]
>>> a[0]
[100, 'BDPS']
>>> a[1]
[1, 2, 10.35, True]
>>> a[0][1]
'BDPS'
>>> a[1][1]
2
>>> a[1][3]
True
>>> a[0][3]
IndexError: list index out of range
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 where x and y are index values;
>>> a=[10,20,30,40,50,60,70,80,90,100]
# elements 3rd to 5th
>>> print(a[2:5])
>>> a[3:5]=[100,200,300,400]
>>> a
[1, 2, 3, 100, 200, 300, 400]
>>>a[1:6]=[10,20]
>>>a
[1,10,20,400]
a=[1,2,3,4,5]
>>> a[1:4]=[100]
>>> a
[1, 100, 5]
Eg:
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> 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([arguments])
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):
x=int(input())
a.append(x)
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]
>>> a=[1,2,3,4]
>>> a.insert(-1,5)
>>> a
[1, 2, 3, 5, 4]
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
>>> a=[1,2,4,2,6,2]
>>> a
[1, 2, 4, 2, 6, 2]
>>> a.remove(2)
>>> a
[1, 4, 2, 6, 2]
pop
Removes and returns an element at the given index in the list. 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]
>>> a=a+b
>>> a
[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]
reverse
Reverse order of the Elements in the list
Syntax:
reverse()
>>> a=[2,1,4,3,6,5]
>>> a
[2, 1, 4, 3, 6, 5]
>>> a.reverse()
>>> a
[5, 6, 3, 4, 1, 2]
Built-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
5) sum(list)
Returns sum of list elements
Program
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))
print("Sum of List :",sum(a))
Tuples
A tuple is a sequence of immutable(Unchanged)
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)
>>> 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)
>>> a=(1,2,3)
>>> b=(4,5,6)
>>>a=a+b
>>>a
(1, 2, 3, 4, 5, 6)
Tuple Methods
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 tuple
count
Return the number of times Element appears in the tuple.
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
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
5) sum(tuple)
Returns sum of tuple elements
Tup_fun.py
n=int(input("Enter No of Elements :"))
x=[]
print("Enter Elements")
for i in range(n):
x.append(int(input()))
a=tuple(x)
print("Given Tuple :",a)
print("Length :",len(a))
print("Max Element :",max(a))
print("Min Element :",min(a))
print("Sum of Elements :",sum(a))
print("Sorted List :",sorted(a))
Strings
Eg:
st=' Hello World! '
st=" Hello World! "
st = '''Hello
Welcome To
Python Programming'''
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'
>>a=[1,2,3,4,5]
>>> str(a)
'[1, 2, 3, 4, 5]'
>>> k=str(a)
>>> k
'[1, 2, 3, 4, 5]'
>>> type(k)
<class 'str'>
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(alphabets) 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(alphabets) 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
split()
Return a list of the words in given string, using the specified 'sep'
syntax:
split(sep=' ')
eg:
>>> st="This is a Book"
>>> st.split()
['This', 'is', 'a', 'Book']
>>> st="abcd*123*ijkl*456"
>>> st.split(sep='*')
['abcd', '123', 'ijkl', '456']
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}
>>> s1=set([3,2,5,1,4])
>>> s1
{1, 2, 3, 4, 5}
>>> s2=set((4,2,1,6,3))
>>> s2
{1, 2, 3, 4, 6}
>>> s3=set("WELCOME")
>>> s3
{'E', 'C', 'O', 'L', 'M', 'W'}
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) (or) a.union(b.union(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}
>>> a={1,2,3,4,5}
>>> b={4,5,6,7,8}
>>> c={4,5,9,10}
>>> print(a&b&c)
{4, 5}
>>> a.intersection(b.intersection(c))
{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 .
Eg1:
>>> a = {1, 2, 3, 4, 5}
>>> b = {4, 5, 6, 7, 8}
>>> print(a - b)
{1, 2, 3}
>>> a.difference(B)
{1, 2, 3}
>>> b-a
{8, 6, 7}
>>> b.difference(a)
{8, 6, 7}
Set Symmetric_Difference
>>a = {1, 2, 3, 4, 5}
>>b = {4, 5, 6, 7, 8}
>>print(a ^ b)
Output: {1, 2, 3, 6, 7, 8}
Eg:
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Note:
1. 'set' object does not support indexing
2. 'set' object doesn't support item deletion using del keyword, but it deletes
entair set
eg: a={1,2,3}
del a
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
3
Set_ope.py
b=set()
print("Enter Second Set")
for i in range(n) :
b.add(int(input()))
'''
print("Union of Two Sets :",a.union(b))
print("Intersection of Two Sets :",a.intersection(b))
print("Difference of Two Sets :",a.difference(b))
print("Symmetric Difference Two Sets :",a.symmetric_difference(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
program
num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
fnum = frozenset(num)
print("frozenset Object is : ", fnum)
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 ).
Note: Dictionary is based on a data structure known as
a hash table.
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
eg3:
>>> d={1:'abcd','a':100,10.25:'H'}
>>> d[1]
'abcd'
>>> d['a']
100
>>> d[10.25]
'H'
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
5.pop(key)
It Removes item of specified key in the dict.
del
eg:
del d['a']
del d
Eg1:
>>> d= {'a':10, 'b':20, 'c':30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> len(d)
3
>>> str(d)
"{'b': 20, 'a': 10, 'c': 30}"
Eg3:
>>> d.values()
dict_values([20, 10, 30])
>>> d.items()
dict_items([('b', 20), ('a', 10), ('c', 30)])
>>> d.keys()
dict_keys(['b', 'a', 'c'])
>>> d.clear()
>>> d
{}
Note:
empty list - []
empty tuple - ()
empty set - set()
empty 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
list instead of an array.
Array.1
print(vals.buffer_info())
(Address) (size)
(1997806967520, 5)
Array.2
vals=array('i',[5,9,-8,4,2])
vals.reverse()
print(vals)
array.3
vals=array('i',[5,9,-8,4,2])
for i in range(5):
print(vals[i])
array.4
vals=array('u',['a','e','i'])
for e in vals:
print(e)
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 addition of two objects using functions
Func1.py
def addition(x,y):
return x+y
Eg2:
To find maximum value of given two values using
user defined functions.
fun2.py
def maxval(x,y):
if x>y :
return x
else :
return y
p,q=max_min(a)
calc.py
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def devide(x,y):
return x/y
def power(x,y):
return (x**y)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Devide")
print("5.Power")
choice=input("Enter choice 1/2/3/4/5:")
num1=int(input("Enter the first number"))
num2= int(input("Enter the second number:"))
if choice =='1':
print(num1, "+", num2,"=", add(num1,num2))
elif choice =='2':
print(num1, "-", num2,"=", subtract(num1,num2))
else:
print("Invalid input")
def func_name(identifier-1,identifier-2=value,…) :
statements
Eg3:
Func4.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 : 300
Maximum value : 25
Maximum value : 50
global_var.py
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 in main block 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 in main block is 8
Local_var.py
def compute(x):
x=x+5
print ("Value of x in function block :", x)
x=10
compute(x)
print ("Value of x in main block :", x)
output:
Value of x in function is 15
Value of x is still 10
Lambda Function
A lambda function is an anonymous(nameless)
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
map() function
Syntax:
map(function, iterable)
Parameters:
Return Value
program:
def square(number):
print(result)
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
k=sum(10)
print ('Sum is', k) -
k=sum(100,200)
print('sum is ',k)
#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
Fact.py
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
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
Recursive(Recursion) 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 Display natural numbers from n to given number using recursive function
Nnos_2.py
def display(x):
print(x,end='\t')
if x > 1:
display(x-1)
n=int(input("Enter any Number :"))
print("Natural number from 1 to",n)
display(n)
#To calculate and Display factorial of given number using recursive function
def factorial(x) :
if x<=1 :
return 1;
else :
return x * factorial(x-1)
Iterator
Iterators is used for looping through collection of data. An
iterator has a __next__() method (or) next() function to get each
value in the sequence.
obj=iter(sequence)
program:
numbers=[100,200,300,400,500]
i = iter(numbers)
while True:
try:
print (i.__next__()) #print (next(i))
except :
break
Generator
A generator is a function that creates an iterator. A generator is a
special type of function which does not return a single value,
instead, it returns an iterator object with a sequence of values. In a
generator function, a 'yield' statement is used rather than a return
statement.
def mygenerator(x):
for i in range(x):
yield i
gen=mygenerator(5)
while True:
try:
print (gen.__next__()) #print (next(gen))
except :
break
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.
Calendar module
It is used to display a calendar of a specified Year or Month or etc.
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(2021)
calendar.prcal(2021,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(2021,10))
eg:
>>> from calendar import prcal
>>> prcal(2021)
cal.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()
math Module
-program:
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 string expression.
Syntax
eval (expression)
eg:
>>> x = 1
>>> eval('x+1')
2
>>> eval('2*2')
4
>>>eval('2+3*5')
17
random module
The choice ()
The choice() method picks and returns a random item from a sequence.
It can be used with lists, tuples, or strings,etc. This Method belongs to
random module, so we import choice from random.
Syntax:
choice(sequence)
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.
ran1.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) :")
ran2.py
- To generate any 5 random numbers from 1 to 10 without duplicate
numbers.
from random import choice
a=[]
while len(a)<5 :
k=choice(range(1,11))
if a.count(k)==0:
a.append(k)
help
it is built-in function and is used to display help content of specified
attribute(function,method,class,varible,module,etc.).
eg1:
>>> import math
>>> help(math.sqrt)
>>> help(math)
Squeezed text (281 lines)
Note:
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
Python - Packages
We organize a large number of files in different folders and
subfolders based on some criteria, so that we can find and manage them
easily. In the same way, a package in Python is basically a
directory(folder) with Python files(modules)and a file with the name
__init__.py
greet.py
def SayHello(name):
print("Hello ", name)
functions.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
test_package.py
from mypackage import greet,functions
greet.SayHello("BDPS")
x=functions.power(3,2)
print("power(3,2) : ", x)
x=functions.sum(10,20)
print("sum of 10 and 20: ", x)
x=functions.average(10,20)
print("Average of 10 and 20 : ", x)
Pip
pip stands for "preferred installer program".
Pip is one of the most famous and widely used package
management system to install and manage software packages written in
Python
Syntax:
Install package
pip install some-package-name
Uninstall package
pip uninstall some-package-name
eg:
pip install pandas
pip uninstall pandas
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)
add_cmd.py
import sys
if len(sys.argv)!=3:
print("Invalid Arguments")
sys.exit()
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.
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
cls_att.py
class test:
'''This is Sample class '''
pass
output
classvariable(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 effect 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.
ob=test()
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)
Accessing Instance Variables
Instance_var.py
class num :
def datainput(self):
self.n=int(input())
def dataoutput(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
def rectarea(self):
return self.l * self.b
r=rect()
s=rect(10,20)
print ("Area of First rectangle is ", r.rectarea())
print ("Area of Second rectangle is ", s.rectarea())
__del__ Method
------------------
It is invoked when the instance is to be destroyed.
This is also called as destructor.
del keyword
del is a keyword and is used to delete (destroy) 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)
s=rect(10,20)
print ("Area of First rectangle is ", r.rectarea())
print ("Area of First rectangle is ", r.l*r.b)
print ("Area of Second rectangle is ", s.rectarea())
print ("Area of Second rectangle is ", s.l * s.b)
def rectarea(self):
return self.__l * self.__b
r=rect(5,8)
s=rect(10,20)
print ("Area of First rectangle is ", r.rectarea())
print ("Area of Second rectangle is ", s.rectarea())
'''
print ("Area of First rectangle is ", r.__l*r.__b)
print ("Area of Second rectangle is ", s.__l* s.__b)
It is not possible,Because l abd b are private members
'''
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(object). 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 invoked 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 (objects) 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 "Base class" and the class which is
extended with the help of inheritance is called derived class . A derived
class always access the members of base class, whereas the base class
never access the members of derived 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.
class derv(base):
pass
d=derv()
d.display()
inr2.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])
inr3.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()
inr4.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.
inr5.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(derv1):
def __init__(self):
derv1.__init__(self)
self.c=300
def display(self):
derv1.display(self)
print("Initial value in derv2 member :",self.c)
d=derv2()
d.display()
inr6.py
class student :
def accept(self) :
self.sno=int(input("Enter Student Number :"))
self.sname=input("Enter Student Name :")
def display(self) :
print("Sudent Number :",self.sno)
print("Sudent Name :",self.sname)
class marks(student) :
def accept(self):
student.accept(self)
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 display(self):
student.display(self)
print("Marks in C :",self.c)
print("Marks in C++ :",self.cpp)
print("Marks in Java :",self.java)
print("Marks in python :",self.python)
def display(self):
print(" RESULT ")
print("--------------------------------------------------")
marks.display(self)
print("Total Marks :",self.tot)
print("Average :%.2f" %(self.avg))
print("Result :",self.result)
print("Grade :",self.grade)
print("---------------------------------------------------")
s=result()
s.calculate_result()
s.display()
Multiple Inheritance
Inr7.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()
inr8.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++,Java and Python ")
self.c=int(input())
self.cpp=int(input())
self.java=int(input())
self.python=int(input())
def display(self):
print("Marks in C :",self.c)
print("Marks in C++ :",self.cpp)
print("Marks in Java :",self.java)
print("Marks in python :",self.python)
def display(self):
print(" RESULT ")
print("--------------------------------------------------")
student.display(self)
marks.display(self)
print("Total Marks :",self.tot)
print("Average :%.2f" %(self.avg))
print("Result :",self.result)
print("Grade :",self.grade)
print("---------------------------------------------------")
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.
Inr9.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()
inr10.py
class base :
def __init__(self,x):
self.a=x
def display(self):
print("Initial value in Base member :",self.a)
class derv1(base) :
def __init__(self):
base.__init__(self,1000)
self.b=100
def display(self):
base.display(self)
print("Initial value in derv1 member :",self.b)
class derv2(base):
def __init__(self):
base.__init__(self,2000)
self.c=200
def display(self):
base.display(self)
print("Initial value in derv2 member :",self.c)
d1=derv1()
d2=derv2()
print("Derv1 Display")
d1.display()
print("\n\nDerv2 Display")
d2.display()
1. Overloading
1. Operator Overloading
2. Method Overloading
3. Constructor Overloading
2. Overriding
1. Method overriding
2. constructor overriding
class Book:
def __init__ (self,price):
self.price=price
def display(self):
print("price is:",self.price)
b1=Book(100)
b2=Book(200)
print("Book1 Price:",end="")
b1.display()
print("Book2 Price:",end=" ")
b2.display()
print('The Total Number of Pages:',b1+b2)
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 (both text and binary files)
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.
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()
f = open('pyt.txt','r')
while True:
line = f.readline()
if len(line) == 0:
break
print (line,end='')
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("pyt.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()
print("Reading data from file")
f = open('text.txt','r')
lines = f.read()
print (lines)
f.close()
2 method
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.seek(0,0)
print("Reading data from file")
lines = f.read()
print (lines)
f.close()
sleep
It is a 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 ch =='' :
break
print (ch,end='')
time.sleep(0.01)
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()
delfilecontent.py
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()
str.encode(code)
codes : utf-8,ascii,etc.
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.
bfile2.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()
bfile3.py
import pickle
class student:
def datainput(self) :
self.id = int(input("Enter Student Id :"))
self.name = input("Enter Student Name :")
self.emailid=input("Enter Email Id :")
def display(self):
print("Student Id :", self.id)
print("Studentr Name:", self.name)
print("Email Id :", self.emailid)
f = open("stu.bin", "ab")
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()
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.
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.
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
try:
name = input('Enter your name : ')
print ('Given name :', name)
except :
print ('Input error has occurred' )
note:
If you want to raise exception press Ctrl+d or Ctrl+c
try:
d=m/n
print ('Division :%.2f'%d)
except TypeError:
print ("You have not entered a numeric value")
except ZeroDivisionError:
print ("You have entered zero value, Division is Not possible")
Nested try
exp4.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.
exp5.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
exp6.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' )
User defined Exceptions
Although Python’s build in exceptions handle most common errors.
We want to create our own exception type to handle situation to our
application. This is quite easy to do, just define a derived class of
Exception(Exception is a pre-defined class) .
exp7.py
class myException(Exception):
def __init__(self,st):
self.mesg = st
def getmessage(self):
return self.mesg
try:
print("Enter any two Numbers ")
s=input()
if(s.isdigit()) :
a=int(s)
else:
ob=myException("Invalid Data")
raise ob
s=input()
if(s.isdigit()) :
b=int(s)
else:
ob=myException("Invalid Data")
raise ob
if b==0 :
ob=myException("Division Error")
raise ob
c=a/b
print("Division :",round(c,2))
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”.
eg:
>>> bin(10)
'0b1010'
>>> hex(43)
'0x2b'
>>> oct(43)
'0o53'
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))
The Python module 're' provides full support for regular expressions
in Python.The 're' module raises the exception re.error if an error occurs
while using a regular expression.
findall:
Returns a list containing all matches
Syntax:
findall(pattern, string)
search :
Returns a Match object if there is a match anywhere in the
string.
Syntax:
search(pattern, string)
split:
Returns a list where the string has been split at each match
syntax:
split(pattern, string)
sub :
Replaces one or many matches with a string
syntax:
sub(pattern, repl, string)
match :
Returns a match object, or None if no match was found.
Syntax:
match(pattern, string)
Patteren
Metacharacters with special meaning:
[] A set of characters
eg: "[a-m]"
. Any character (except newline character)
eg: "he..o" - hello
^ Starts with
eg: "^hello"
$ Ends with
eg: "hello$"
etc.
programs:
re1.py
import re
re2.py
import re
output: ['hello']
re4.py
import re
txt = "BDPS COMPUTER EDUCATION"
x = re.findall("^BDPS", txt)
if x:
print("Yes, the string starts with BDPS ")
else:
print("No match")
x = re.findall("EDUCATION$", txt)
if x:
print("Yes, the string ends with EDUCATION ")
else:
print("No match")
re5.py
import re
txt = "The rain in Spain"
x = re.search("Sp", txt)
if x:
print("YES! We have a match!")
else:
print("No match")
output:
YES! We have a match!
re6.py
import re
txt = "The rain in Spain"
#Check if the string starts with "The" and ends with "Spain":
x = re.search("^The.*Spain$", txt)
if x:
print("YES! We have a match!")
else:
print("No match")
output:
YES! We have a match!
re7.py
import re
re8.py
import re
import re
txt = "The rain in Spain"
x = re.match("The.*Spain", txt)
if x:
print("YES! We have a match!")
else:
print("No match")
Tkinter Programming
Tkinter is the standard GUI library for Python. Tkinter provides a fast
and easy way to create GUI applications.
Tk()
window of an application.
geometry()
Syntax:
geometry("Width x Height")
eg: geometry("300x200")
title()
Syn:
title(str)
mainloop()
Eg:
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 − Here is the list of most commonly used options for this
widget..
Options :
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.Checkbutton
Syntax
options: width,height,onvalue,offvalue,etc.
gui3.py
top = Tk()
C1.pack()
C2.pack()
top.mainloop()
3.Label
This widget implements a display box where you can place text or images.
Syntax
Syntax
Gui4.py
top = Tk()
E = Entry(top)
E.pack(side = RIGHT)
top.mainloop()
5.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
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
root.mainloop()
6.Listbox
The Listbox widget is used to display a list of items from which a user
can select items.
syntax
insert :
insert(index,item)
gui6.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()
7.Toplevel
Syntax
Gui7.py
from tkinter import *
top = Tk()
top.geometry("300x100")
def func():
ob=Toplevel()
ob.title("MYWINDOW")
B.pack()
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.
pymysql/MySQLdb
pymysql/MySQLdb is an interface for connecting Python code
to a MySQL database server. You can insert, fetch, delete, and
update database tables by writing simple SQL statements and
executing through Python code.
MYSQL COMMANDS-1
1.Create a database on the mysql server :
create database database_name ;
eg: create database mydb;
3.Switch to a database :
use databasename ;
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="bdps",db="mydb")
print("Connected to Database")
except :
print("Unable to Connect 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);
2.To see all the tables in the database:
show tables;
4. To Delete a table :
drop table table_name;
eg:
insert into emp values(100,'abc',20000.00)
cursor()
This Method belongs to connection object ,it returns 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:
cursorobject. execute(sql statement)
close()
It Closes the cursor object.
db2.py
import pymysql
try:
conn=pymysql.connect (host="localhost",user="root",passwd="bdps",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")
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.
rollback():
This method belongs to connection object.The rollback() method
cancels all the modifications applied to the database table. It keeps the
database table when it was last saved.
Db3.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="bdps",db="mydb")
cursor=conn.cursor()
cursor.execute (''' insert into emp values (100, 'aaa', 25000.00) ''')
print("One Row Inserted")
cursor.close()
conn.commit()
conn.close()
except :
print ("Unable to insert Row")
db4.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="bdps",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 values (%d,'%s',%f)
'''%(eno,ename,salary))
print("One Row Inserted")
conn.commit()
except:
print ("Unable to insert Row")
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 Connect")
fetchone():
This method belongs to cusor object and it fetches one row from resultset.
fetchall():
This method belongs to cusor object and it fetches all the rows from resultset.
db5.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="bdps
",db="mydb")
cursor=conn.cursor()
try:
cursor.execute ("SELECT * from emp")
print ("ENO\t\tENAME\t\tSALARY")
print("----------------------------------------------------------")
while True:
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")