PYTHON Complete Notes With QB
PYTHON Complete Notes With QB
PYTHON Complete Notes With QB
Unit I
Introduction to Python - Python Interpreter - Data types - Identifiers and keywords - Integral Types
- Floating Point Types – Strings
Introduction to Python
Features of Python
Programmers can easily interact with the interpreter directly at the python prompt
to write their programs.
e) Open source
Python is publicly available open source software.
f) Portable
High level languages are portable which means they are able to run across all
major hardware and software platforms with few or no change in source
code.
g) Interpreted
Python programs are interpreted, i.e., the interpreter takes the source code as input,
(to portable byte-code) one statement at a time and executes it immediately.
There is no need for compiling and linking.
h) Object Oriented
Python supports both Procedure-Oriented and Object-Oriented Programming
(OOP) approaches.
In procedure-oriented language, the program is built around procedures (functions).
In object-oriented languages, the program is built around objects which combines
data and functionality.
When compared to other languages like Java or C++, Python is the simplest object
oriented programming language available today.
i) Embeddable
Programmers can embed python within their C, C++, COM, ActiveX, CORBA and
Java programs to give ‘scripting’ capabilities for users.
j) Extensive libraries
Python has a huge library that is easily portable across different platforms.
These library functions are compatible on UNIX, Windows, Macintosh, etc. and
allows programmers to perform wide range of applications varying from text
processing, maintaining databases, to GUI Programming.
k) Dynamically types
Python is a dynamically typed language, which means there is no need to declare
variables explicitly.
Programs run immediately without taking much time to link and compile.
l)
Compiler vs. Interpreter
Compiler Interpreter
Scans the entire program and Translates one statement at a time
translates it as a whole into machine
code
It takes large amount of time to analyze It takes less amount of time to analyze
the source code but the overall the source code but the overall
execution time is comparatively faster execution time is slower
Generates intermediate object code No intermediate object code is
which further requires linking, hence generated, hence memory is efficient
requires more memory
It generates error message only after Continues translating the program until
scanning the whole program, Hence the first error is met, in which case it
debugging is comparatively hard stops. Hence debugging is easy.
Programming languages such as C and Programming languages such as
C++ use compilers Python and Ruby use interpreters
Python Interpreter
o The first three lines are the information about python version number and operating
system.
o The last line >>> is a prompt (chevron) that indicates that the interpreter is ready
to enter code.
o If the user types a line of code and hits enter the interpreter displays the result.
o Drawback:
o We cannot save the statements and have to retype all the statements
once again to re-run them.
Script mode
o Basically a script is a text file containing python statements.
o Scripts are saved to disk for future use.
o Python scripts have the extension .py, meaning that the filename ends with .py
2. An untitled blank script text editor will be displayed on screen as shown below
a =100
b = 350
c = a+b
Comments in Python
#swap.py
#Swapping the values of two variable program
#written by V.Balamurugan, April 2019
"""swap.py
Swapping the values of two variable program
written by V.Balamurugan, April 2019"""
A program needs to interact with the user to accomplish the desired task; this can be
achieved using Input-Output functions.
The input () function helps to enter data at run time by the user and the output function
print () is used to display the result of the program on the screen after execution.
The print () function
o In python print () function is used to display the result on the screen.
o The syntax for print () is as follows:
print(“String to be displayed as output”)
print(variable)
Output Formatting
o Sometimes we would like to format out output to make it look attractive.
o This can be done by using the str.format() method
Example Output
>>> x=10;y=20 The values of x is 10 and y is
>>> print('The values of x is {} and y is {}'.format(x,y)) 20
>>> print('I am studying {0} and {1}'.format('BE','CSE')) I am studying BE and CSE
>>> print('Hello {a},{b}'.format(b='good morning',a='Muni')) Hello Muni,good morning
>>> x=123.456789 The value of x is 123.46
>>> print('The value of x is %.2f'%x)
>>> name='Muni' Muni is 40 years old.
>>> age=40
>>> print("%s is %s years old."%(name,age))
>>> price=150 The Apple costs 150 rupees
>>> fruit='Apple'
>>> print("The %s costs %d rupees"%(fruit,price))
The input() function
o The input () function is used to accept an input from a user.
o A programmer can ask a user to input a value by making use of input().
Python uses whitespace such as spaces and tabs to define program blocks whereas other
languages like C, C++, java use curly braces { } to indicate blocks of codes for class,
functions or body of the loops and block of selection command.
The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all
statements within the block must be indented with same amount spaces.
Example
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
Tokens
Python breaks each logical line into sequence of elementary lexical components known
as Tokens.
A token is the smallest unit of the program.
The normal token types are:
o Identifiers/Variables
o Keywords
o Operators
o Delimiters
o Literals
Keywords
We cannot use a keyword as variable name, function name or any other identifier.
and assert break class continue def del elif else Except
exec finally for from global if import in is Lambda
not or pass print raise return try while with yield
Python Operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Types of Operators
o Arithmetic Operators
o Comparison Operators
o Logical Operators
o Assignment Operator
o Membership Operator
o Identity Operator
o Bitwise Operator
o Conditional Operator
Arithmetic Operator
o An arithmetic operator is a mathematical operator that takes two operands and
performs a calculation on them.
Comparison Operators
o A Relational operator is also called as Comparative operator which checks the relationship
between two operands.
o If the relation is true, it returns true; otherwise it returns False.
Logical Operators
o In python, Logical operators are used to perform logical operations on the given
relational expressions. There are three logical operators they are and, or and not.
Assignment Operators
o In Python, = is a simple assignment operator to assign values to variable.
Conditional Operator
o Ternary operator is also known as conditional operator that evaluate something
based on a condition being true or false.
o The Syntax conditional operator is,
Membership Operators
o Membership Operators are used to test whether a value or variable is found in a
sequence (list, sting, tuple, dictionary and set).
o in and not in are two membership operators.
& Bitwise AND X&Y Both operands are true result is true
<< Bitwise left shift X<<2 Operands are shifted left by number
of times specified
Operator Description
Python Delimiters
Python uses the symbols and symbol combinations as delimiters in expressions, lists,
dictionaries and strings. Following are the delimiters.
Python Literals
Values
Values are the basic units of data, like a number or a string that a program manipulates.
Examples: 2, 42.0, and ‘Hello, World!’
These values belong to different types: 2 is an integer, 42.0 is a floating point number,
and ‘Hello, World!’ is a string.
Types
Integer Type
Integers are whole numbers with no fractional part and decimal point.
They can be either positive, negative or zero value.
To write an integer in decimal (base 10), the first digit must not be zero
Example
>>> c=1458935
>>> type(c)
<class 'int'>
An octal literal (Base 8) is a number prefixed with 0 (zero) followed by either uppercase
O or lowercase o.
Example
>>> oct_lit=0O24 # Uppercase O
>>> print(oct_lit)
20
A hexadecimal literal (Base 16) is prefaced by a 0 (zero) followed by an uppercase X
or a lowercase x.
Example
>>> hex_literal=0x77
>>> print(hex_literal)
119
A binary literal (base 2) is of the form 0 (zero) followed by either an uppercase B or
lowercase b.
Example
>>> bin_lit=0b1010
>> print(bin_lit)
10
Bigger whole numbers are called as long integers.
For example, 535633629843L is a long integer.
Note that long integer must have ‘l’ or ‘L’ as the suffix.
However, remember that commas are never used in numeric literals or numeric values.
Therefore the numbers like 3,567,-8,904, are not allowed in Python.
NOTE:
Arithmetic overflow may occur when a calculated result is too large in
magnitude (size). For example, just you try to multiple 2.7e200 *4.3e200. You
will ge result as inf
Arithmetic underflow occurs when the result is too small in magnitude to be
represented.
Loss of precision problem
o When we divide 1/3 we know that results is .33333333…, where 3 is
repeated infinitely.
o Since any floating point number has a limited precision and range, the
result is just approximation of the true value.
Complex Type
Complex numbers are of form, x+yj, where x is the real part and y is the imaginary part
Example
>>> z=5+14j
>>> z.real
5.0
>>> z.imag
14.0
>>> print(z)
(5+14j)
>>> print((2+3j)*(4+5j))
(-7+22j)
String Type
Boolean Type
List Type
Lists are created by placing all items inside a square bracket separated by commas
Operations on List
Indexing
Slicing
Concatenation
Repetitions
Tuple Type
A tuple is same as list, except that the set of elements is enclosed in parentheses instead of
square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to
a tuple or remove elements from the tuple.
Benefits of Tuple:
o Tuples are faster than lists.
o If the user wants to protect the data from accidental changes, tuple can be used.
Basic Operations
>>> t[0]='a'
t[0]='a'
Mapping
Dictionaries
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
Tuple Assignment
Example:
>>> T1=(10,20,30)
>>> T2=(100,200,300,400)
>>> print(T1)
>>> print(T2)
>>> T1,T2=T2,T1
>>> print(T1)
>>> print(T2)
Strings in Python
In python strings are simple text consisting of sequence of characters, letters, numbers,
and special characters.
Strings can be created using single quotes, double quotes and triple quotes.
Using triple quotes, strings can span several lines without using the escape character.
Example Output
>>> str1='Hello' >>> print(str1)
>>> str2="Hello" Hello
>>> str3=="""Good morning everyone >>> print(str2)
Welcome to python programming Hello
Happy reading""" >>>print(str3)
Good morning everyone
Welcome to python programming
Happy reading
Example Output
>>> s='Computer' Computer
>>> print(s[-1]) r
>>> print(s[-8]) C
>>> print(s[0]) C
>>> print(s[-5]) p
String Immutability
Character sequences fall into two categories i.e., Mutable and immutable.
Mutable means changeable.
Immutable means unchangeable.
Hence strings are immutable sequence of characters.
Example Output
>>> str1="I Love Python" TypeError: 'str' object does not support item
>>> str1[0]="U" assignment
>>> str1="I Love Python" U Love Python
>>> str2="U"+str1[1:]
>>> print(str2)
Operations on Strings
String Slices
Example Explanation
S="IIT-MADRAS" Prints the entire string
>>> S[::]
'IIT-MADRAS'
>>> S[::-1] Display the string in Reverse Order
'SARDAM-TII'
>>> S[0:len(S):2] Selects the portion of the string which starts at
'ITMDA' index 0 and ends index 10. The step size is 2.
It means that we first extract a slice or a portion
of the string which starts with the index 0, ends
with the index 10 and selects every other
character from String S
Format method
Example Explanation
>>> print(format('Python Programming','<40')) Left Justification
‘Python Programming ’
>>> print(format('Python Programming','>40')) Right Justification
‘ Python Programming’
>>> print(format('Python Programming','^40')) Center
‘ Python Programming ’
Escape sequences
In the above example python got confused as to where the string starts and ends.
So, we need to clearly specify that this single quote does not indicate the end of the
string.
The indication can be given with the help of escape sequences.
Example Output
>>> print('What\'s your name?') What's your name?
>>>print("The boy replies, \"My name is Aadithya.\" ") The boy replies, "My name is
Aadithya."
>>> print("Today is 15th August. \n India became Today is 15th August.
independent on this day") India became independent on this
day
>>> print("Today is 15th August. \t India became Today is 15th August. India
independent on this day") became independent on this day
Traversing a string
Traversing a string means accessing all the elements of the string one after the other by
using subscript.
A string can be traversed using : for loop, while loop
Example Output
>>> bird='parrot' Parrot
>>> for letter in bird:
print(letter,end="")
S="ILOVEPYTHONPROGRAMMING" IOEYHNRGAMN
for ch in range(0,len(S),2):
print(S[ch],end=" ")
Traversal using while loop
Example Output
>>> bird='parrot' p
>>> i=0 a
>>> while i<len(bird): r
letter=bird[i] r
print(letter) o
i=i+1 t
Syntax: Stringname.method()
a=“happy birthday”
Worked Examples
radius=int(input()) 10
pi=3.14 314.00
area=pi*radius*radius
print('%.2f'%area)
Write a Python-Program to convert Fahrenheit to Output
Celsius by reading a Fahrenheit value from User in a
float variable.
x=float(input("Enter temperature in Fahrenheit:")) Enter temperature in Fahrenheit: 98.6
cl=(x-32)/1.8 Temperature in Celsius: 37.00
print('\nTemperature in Celsius: %.2f'%cl)
Calculating Simple Interest Output
P=int(input("Enter the principal amount")) Enter the principal amount10000
N=float(input("\nEnter the rate of interest"))
R=int(input("\nEnter the time period (in years)")) Enter the rate of interest7
SI=(P*N*R)/100
print('\nSimple Interest is %.2f'%SI) Enter the time period (in years)10
Part- A
1. Define python
Python is widely used general-purpose, high-level, interpreted, interactive,
object-oriented and reliable programming language.
It was created by Guido van Rossum, and released in 1991.
Python got its name from a BBC comedy series from seventies- “Monty Python’s
Flying Circus”.
Python has a simple syntax similar to the English language.
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
It has vast library of modules to support integration of complex solutions from
pre-built components.
2. Give the features of python
Easy to Use:
Expressive Language
Interpreted Language
Cross-platform language
Free and Open Source
Object-Oriented language
Extensible
3. What is python interpreter?
The engine that translates and runs Python is called the Python Interpreter:
There are two ways to use it: interactive mode and script mode.
The >>> is called the Python prompt. The interpreter uses the prompt to indicate
Compiler Interpreter
Scans the entire program and Translates one statement at a time
translates it as a whole into machine
code
It takes large amount of time to analyze It takes less amount of time to analyze
the source code but the overall the source code but the overall
execution time is comparatively faster execution time is slower
Generates intermediate object code No intermediate object code is
which further requires linking, hence generated, hence memory is efficient
requires more memory
It generates error message only after Continues translating the program until
scanning the whole program, Hence the first error is met, in which case it
debugging is comparatively hard stops. Hence debugging is easy.
Programming languages such as C and Programming languages such as
C++ use compilers Python and Ruby use interpreters
and assert break class continue def del elif else Except
exec finally for from global if import in is Lambda
not or pass print raise return try while with yield
10. Outline the logic to swap the content of two variables without using third variable.
[May 2019]
a,b=b,a
>>> n = 17
>>> pi = 3.14159
12. Write the differences between the symbol / and // in python
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operator
Logical Operators
Bitwise Operators
Membership Operators
Identity Operator
15. State about logical operators available in python [Apr /May 2019]
16. Write a python code to display the digit’s at one’s place of a number
digit_at_ones_place=a%10
Part-B
Unit II
Case Sensitive - Scripts - Sequence Types - Tuples - Named Tuples - Sets - Mapping Types -
Dictionaries -Generators – Iterators
Case Sensitive
Scripts
2. An untitled blank script text editor will be displayed on screen as shown below
a =100
b = 350
c = a+b
Reverse -8 -7 -6 -5 -4 -3 -8 -1
Indexing
List values 1 2 3.4 5 6.789 Python 1+2i X
Forward 0 1 2 3 4 5 6 7
indexing
Example Output
>>> Marks = [10, 23, 41, 75] 10
>>> print (Marks[0])
>>> Marks = [10, 23, 41, 75] 75
>>> print (Marks[-1])
Example Explanation
>>> L1=[10,20,30,40,50] The L1[1:4] returns the subset of list starting from
>>> L1[1:4] the start index 1 to one index less than that of end
[20, 30, 40] index, i.e. 4-1=3
Slices Examples
a[0:3] >>> a=[9,8,7,6,5,4]
>>> a[0:3]
[9, 8, 7]
a[:4] >>> a[:4]
[9, 8, 7, 6]
a[1:] >>> a[1:]
[8, 7, 6, 5, 4]
a[:] >>> a[:]
[9, 8, 7, 6, 5, 4]
a[2:2] >>> a[2:2]
[]
a[0:6:2] >>> a[0:6:2]
[9, 7, 5]
a[::-1] >>> a[::-1]
[4, 5, 6, 7, 8, 9]
Example Program using Slicing Output
print("*******List Slicing Example*****") *******List Slicing Example*****
Nos_List=[1,2,3,4,5,6,7,8,9,10,11] Elements 3rd to 5th : [3, 4, 5]
print("Elements 3rd to 5th :",Nos_List[2:5]) Elements begining upto -5th index: [1, 2,
print("Elements begining upto -5th index:",Nos_List[:-5]) 3, 4, 5, 6]
print("Elements 6th to end:",Nos_List[5:]) Elements 6th to end: [6, 7, 8, 9, 10, 11]
print("Elements begining to end:",Nos_List[:]) Elements beginning to end: [1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11]
List Methods
Example:
>>> seq=[1,2,3,4,5]
>>> seq1=[1,2,3,1,4,1,5]
>>> seq.count(4)
1
>>> seq1.count(1)
3
b) index(value) Returns the index value of the first recurring
Syntax: list_name.index(value) element
Example:
>>> seq.index(4)
3
>>> seq.index(1)
0
c) index(value,start) Returns the index of the given value which
Syntax: list_name.index(value,start) appears first in the list
Example:
>>> seq.index(4,1)
3
>>> seq1.index(1,2)
3
>>> seq1.index(1,4)
5
2. Returns the value but changes the list
>>> seq1.remove(1)
>>> seq1
[2, 3, 1, 4, 1, 5]
e) reverse() Reverses the order of the element in the list.
Example:
>>> seq.reverse()
>>> print(seq)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
f) sort() Sorts the element in list.
Example:
>>> seq1.sort()
>>> print(seq1)
[1, 1, 2, 3, 4, 5]
g) pop() Removes the last element from the list
Example:
>>> seq1.pop()
5
List Aliasing
[1,2,3,4]
Nos_List
temp_List
List Aliasing
List Cloning
Cloning list is to make a copy of the list itself, not just the reference.
Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 8
Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202
>>> a=["one","two","three"]
>>> del a[1]
>>> a
['one', 'three']
You can use slice as an index for del:
>>> list=['a','b','c','d','e','f']
>>> list
['a', 'f']
List Comprehensions
List comprehension is a simplest way of creating sequence of elements that satisfy a certain
condition.
Syntax for List Comprehension
Nested Lists
Nested lists are list objects where the elements in the lists can be lists themselves.
>>> li[2][:] # Prints entire list stored at [30, 40, 50, 60, 70, 80]
position
>>> li[2][1:4] # Slicing operation [40, 50, 60]
>>> li[2][::] # Prints entire list stored at [30, 40, 50, 60, 70, 80]
position 2
>>> li[2][::2] # Increments nested list by 2 [30, 50, 70]
>>> li=[[1,2,3],[4,5,6],[7,8,9]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> li[0] # Accessing 0th index [1, 2, 3]
>>> li[1] # Accessing 1st index [4, 5, 6]
>>> li[2] # Accessing 2nd index [7, 8, 9]
Tuples
A tuple is same as list, except that the set of elements is enclosed in parentheses instead
of square brackets.
They are immutable sequences.
The elements in the tuple cannot be modified as in lists.
But tuple can be converted into list and list can be converted in to tuple.
Benefits of tuples
Creating tuples
In a list, elements are defined within square brackets, whereas in tuples, they may be
enclosed by parenthesis.
The elements of a tuple can be even defined without parenthesis.
Syntax:
# Empty Tuple
Tuple_Name=( )
Example 1:
>>> MyTup1=(23,56,89,'A','E','I','Tamil')
>>> print(MyTup1)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
Example 2:
>>> MyTup2=23,56,89,'A','E','I','Tamil'
>>> print(MyTup2)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
Syntax:
Tuple_Name = tuple( [list elements] )
Example :
>> MyTup3=tuple([25,45,90])
>>> print(MyTup3)
(25, 45, 90)
>>> type(MyTup3)
<class 'tuple'>
While creating a tuple with a single element, add a comma at the end of the element.
In the absence of a comma, Python will consider the element as an ordinary data type; not
a tuple.
Creating a Tuple with one element is called “Singleton” tuple.
Example :
>>> MyTuple4=(10)
>>> type(MyTuple4)
<class 'int'>
>>> MyTuple5=(10,)
>>> type(MyTuple5)
<class 'tuple'>
Like list, each element of tuple has an index number starting from zero. The elements of a
tuple can be easily accessed by using index number.
Example Output
>>> Tup1 = (12, 78, 91, "Tamil", "Telugu", 3.14, 69.48) (12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
>>> print(Tup1)
>>> print(Tup1[2:5]) (91, 'Tamil', 'Telugu')
>>> print(Tup1[:5]) (12, 78, 91, 'Tamil', 'Telugu')
>>> print(Tup1[4:]) ('Telugu', 3.14, 69.48)
>>> print(Tup1[:]) (12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
Example :
# Program to Join two tuples
Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)
Output
(2, 4, 6, 8, 10, 1, 3, 5, 7, 9)
To delete an entire tuple, the del command can be used.
Syntax:
del tuple_name
Example :
Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ", Tup1)
del Tup1
print (Tup1)
Output
The elements of Tup1 is (2, 4, 6, 8, 10)
Traceback (most recent call last):
File "D:/Python/Tuple Examp 1.py", line 4, in <module>
print (Tup1)
NameError: name 'Tup1' is not defined
Operations on Tuples
>>> (1,2)+(3,4)
(1, 2, 3, 4)
The * Operator: The multiplication operator is used to replicate the elements of tuple.
>>> (1,2)*3
(1, 2, 1, 2, 1, 2)
Tuple Assignment
Tuple assignment is an assignment with a sequence on the right side and a tuple of variables
on the left.
The right side is evaluated and then its elements are assigned to the variables on the left.
Example :
>>> (a, b, c) = (34, 90, 76)
>>> print(a,b,c)
34 90 76
>>> (x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
>>> print(x,y,z,p)
4 5.666666666666667 1 False
Note: When we assign values to a tuple, ensure that the number of values on both sides of the
assignment operator are same; otherwise, an error is generated by Python.
A function can return only one value at a time, but Python returns more than one value
from a function. Python groups multiple values and returns them together.
Named Tuples
One can access the values stored in Named Tuple using the following
o Indexes
o Keys
o getattr()
The _make() method can be used to convert an iterable object like list, tuple, etc to
NamedTuple object.
We can also convert a dictionary type object to NamedTuple object. For this conversion,
we need the ** operator.
NamedTuple can return the values with keys as OrderedDict type object. To make it
OrderedDict, we have to use the _asdict() method.
e1=Employee._make(my_list)
print(e1)
#Convert Dict to named tuple
my_dict={'name':'Bala','city':'Chennai','salary':'30000'}
e2=Employee(**my_dict)
print(e2)
#Show the named tuple as dictionary
emp_dict=e1._asdict()
print(emp_dict)
Sets
Creating Sets
A set is created by placing all the elements separated by comma within a pair of curly
brackets.
The set ( ) function can also used to create sets in Python.
Syntax :
Example :
>>> S1={1,2,3,'A',3.14}
>>> print(S1)
{1, 2, 3, 3.14, 'A'}
>>> S2={1,2,2,'A',3.14}
>>> print(S2)
{1, 2, 'A', 3.14}
In the above examples, the set S1 is created with different types of elements without
duplicate values.
Whereas in the set S2 is created with duplicate values, but python accepts only one element
among the duplications.
Which means python removed the duplicate value, because a set in python cannot have
duplicate elements.
Note: When you print the elements from a set, python shows the values in different order.
Example :
MyList=[2,4,6,8,10]
MySet=set(MyList)
print(MySet)
Output:
{2, 4, 6, 8, 10}
Set Operations
1. issubset()
Returns True if all items of set s are present in set t
Example 1: Example 2:
s={1,2,3} s={1,2,3}
t={1,2,3,4,5,6} t={1,2,3,4,5,6}
print(s.issubset(t)) print(s<=t)
Output: Output:
True True
2. issuperset()
Return True if all items of set t are present in set s
Example 1: Example 2:
s={1,2,3} s={1,2,3}
t={1,2,3,4,5,6} t={1,2,3,4,5,6}
print(s.issuperset(t)) print(s>=t)
Output: Output:
False False
3. Union
Return a set that contains all items from both sets, duplicates are excluded.
In python, the operator | is used to union of two sets.
The function union ( ) is also used to join two sets in python.
Example 1: Example 2:
s={1,2,3} s={1,2,3}
t={1,2,3,4,5,6} t={1,2,3,4,5,6}
a=s.union(t) a=s|t
print(a) print(a)
Output Output
{1,2,3,4,5,6} {1,2,3,4,5,6}
4. Intersection
It common elements in two sets.
The operator & is used to intersect two sets in python.
The function intersection ( ) is also used to intersect two sets in python.
Example 1: Example 2:
s={1,2,3} s={1,2,3}
t={1,2,3,4,5,6} t={1,2,3,4,5,6}
a=s.intersection(t) a=s&t
print(a) print(a)
Output Output
{1,2,3} {1,2,3}
5. Difference
The below example will return a set that contains the items that only exist in set s, and
not in set t
Example 1: Example 2:
s={1,2,3} s={1,2,3}
t={1,2,3,4,5,6} t={1,2,3,4,5,6}
a=s.difference(t) a=s-t
print(a) print(a)
Output Output
{} {}
The below example will return a set that contains the items that only exist in set t, and
not in set s
Example 1: Example 2:
s={1,2,3} s={1,2,3}
t={1,2,3,4,5,6} t={1,2,3,4,5,6}
a=t.difference(s) a=t-s
print(a) print(a)
Output Output
{4,5,6} {4,5,6}
6. Symmetric Difference
It includes all the elements of both sets except the common elements.
The caret (^) operator is used to perform symmetric difference set operation in python.
The function symmetric_difference( ) is also used to do the same operation.
Example 1: Example 2:
s={1,2,3,7,8,9} s={1,2,3,7,8,9}
t={1,2,3,4,5,6} t={1,2,3,4,5,6}
a=s.symmetric_difference(t) a=s^t
print(a) print(a)
Output Output
{4, 5, 6, 7, 8, 9} {4, 5, 6, 7, 8, 9}
Set Methods
update() set1.update(set2) s.update(t) The update() method inserts the items in set2
{1,2,3,6,4,5} into set1
Dictionaries
Dictionary is a data structure in which we can store values as a pair of key and value.
Each key is separated from its value by a colon (:), and consecutive items are
separated by commas.
The entire items in a dictionary are enclosed in curly braces. ({}).
Creating a Dictionary
Syntax :
dictionary_variable= { }
Example
dict={}
print(dict)
Output
{}
Syntax :
Syntax :
dict([(key 1,value 1),(key 2, value 2,….])
Example
print(dict([('Roll_No','16/001'),('Name','Arnav'),('Course','BTech')]))
Output
{'Roll_No': '16/001', 'Name': 'Arnav’, 'Course': 'BTech'}
Dictionary Comprehensions
o In Python, comprehension is another way of creating dictionary.
Syntax :
Dict = { expression for variable in sequence [if condition] }
Example
dict={x:x**2 for x in range(5) if x%2==0}
print(dict)
Output
{0: 0, 2: 4, 4: 16}
Accessing Values
To access values in a dictionary, square brackets are used along with the key to obtain its
value.
Example
dict={"Name":"Arav","Dept":"IT","RNo":123}
print(dict)
print(dict["Name"])
print(dict["Dept"])
print(dict["RNo"])
Output
{'Name': 'Arav', 'RNo': 123, 'Dept': 'IT'}
Arav
IT
123
Syntax :
dictionary_variable[key]=value
Example
dict={"Name":"Arav","Dept":"IT","RNo":123}
dict['Course']="BTECH"
print(dict)
Output
{'RNo': 123, 'Name': 'Arav', 'Dept': 'IT', 'Course': 'BTECH'}
Modifying an entry
To modify an entry, just overwrite the existing value as shown in following example
Syntax :
dictionary_variable[ existing_key]=new_value
Example
dict={"Name":"Arav","Dept":"IT","RNo":123}
dict['Course']="MTECH"
print(dict)
Output
{'RNo': 123, 'Name': 'Arav', 'Dept': 'IT', 'Course': 'MTECH'}
Deleting items
Syntax :
del dictionary_variable[key] # deletes the given key pair
del dictionary_variable # Removes the dictionary from memory
dictionary_variable.clear() # Clears all key value pairs from dictionary
Example
dict={"Name":"Arav","Dept":"IT","RNo":123}
dict['Course']="MTECH"
print(dict)
del dict['Course']
print("After deleting Course:",dict)
dict.clear()
print(dict)
del dict
print("Dict does not exists......")
print(dict)
Output
{'RNo': 123, 'Name': 'Arav', 'Dept': 'IT', 'Course': 'MTECH'}
After deleting Course: {'RNo': 123, 'Name': 'Arav', 'Dept': 'IT'}
{}
Dict does not exists......
NameError: name 'Dict' is not defined
Properties of dictionary keys
Keys must have unique values. Not even a single key can be duplicated in a dictionary.
If you try to add a duplicate key, then the last assignment is retained.
Example Output
dict={"Name":"Arav","Dept":"IT","RNo":123,"Name":"Keerthi"} {'Name': 'Keerthi', 'Dept': 'IT', 'RNo':
print(dict) 123}
In a dictionary, keys should be strictly of a type that is immutable. This means that a key
can be of string, number, or tuple type but it cannot be a list which is mutable
Example Output
dict={["Name"]:"Arav","Dept":"IT","RNo":123,"Name": Traceback (most recent call last):
"Keerthi"} File "main.py", line 8, in <module>
print(dict)
dict={["Name"]:"Arav","Dept":"IT","RNo":12
3,"Name":"Keerthi"}
TypeError: unhashable type: 'list'
Dictionary Methods
Iterators in Python
Iterator in python is any python type that can be used with a ‘for in loop’.
Python lists, tuples, dictionaries and sets are all examples of inbuilt iterators.
Technically, in Python, an iterator is an object which implements the iterator protocol,
which consist of the methods __iter__() and __next__().
__iter__ method that is called on initialization of an iterator. This should return an object
that has a next or __next__ (in Python 3) method.
next ( __next__ in Python 3) The iterator next method should return the next value for the
iterable.
When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next () on the
iterator object.
This method should raise a StopIteration to signal the end of the iteration.
To create an object/class as an iterator you have to implement the methods __iter__() and
__next__() to your object.
All classes have a function called __init__(), which allows us do some initializing when
the object is being created.
The __iter__() method acts similar, we can do operations (initializing etc.), but must always
return the iterator object itself.
The __next__() method also allows us to do operations, and must return the next item in
the sequence.
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
StopIteration
The example above would continue forever if we had enough next () statements.
To prevent the iteration to go on forever, we can use the StopIteration statement.
In the __next__() method, we can add a terminating condition to raise an error if the
iteration is done a specified number of times:
Generators in Python
Python Generators are the functions that return the traversal object and used to create
iterators.
It traverses the entire items at once.
There is a lot of complexity in creating iteration in Python; we need to implement __iter__()
and __next__() method to keep track of internal states.
It is a lengthy process to create iterators. That's why the generator plays an essential role
in simplifying this process. If there is no value found in iteration, it raises StopIteration
exception.
Generator Object
Generator functions return a generator object. Generator objects are used either by calling
the next method on the generator object or using the generator object in a “for in” loop
# x is a generator object
x = simpleGeneratorFun()
yield vs return
The yield statement is responsible for controlling the flow of the generator function. It
pauses the function execution by saving all states and yielded to the caller. Later it resumes
execution when a successive function is called. We can use the multiple yield statement in
the generator function.
The return statement returns a value and terminates the whole function and only one
return statement can be used in the function.
Generator Expression
The representation of generator expression is similar to the Python list comprehension. The
only difference is that square bracket is replaced by round parentheses.
Generator Advantages
Easy to implement
Memory efficient
Generate Infinite Sequence
Worked Examples
del Num[index]
print("The list after deleting even numbers = ", Num)
Program to perform linear search Output
my_data=[89,45,9,21,34] Enter number to search:34
num=int(input("Enter number to search:")) Item is located at the position= 4
found=0
for i in range(0,len(my_data)):
if(num==my_data[i]):
print("Item is located at the position=",i)
found=1
break
if(found==0):
print("%d is not in list"%num)
Sum of elements in a list Output
my_data=[89,221,8,23] Sum of elements in the list= 341
sum=0
for i in my_data:
sum=sum+i
print("Sum of elements in the list= ",sum)
Write a program that converts a list of temperatures in Celsius Output
into Fahrenheit
def convert_to_f(Temp_C): (36.5, 37, 37.5, 39)
return((float(9)/5)*Temp_C+32) [97.7, 98.60000000000001, 99.5,
Temp_C=(36.5,37,37.5,39) 102.2]
Temp_F=list(map(convert_to_f,Temp_C))
print(Temp_C)
print(Temp_F)
Write a Python program: Output
To display the elements first and last element from tuple
To find the minimum element from tuple
To add all elements in the tuple
To display same tuple element multiple times
a=input("Enter the tuple\n") Enter the tuple
l=list(map(int,a.split(","))) 1,2,3,4,5
t=tuple(l) 1.Print first and last element
while True: 2.Minimum element
resp=int(input("1.Print first and last element\n2.minimum 3.Sum of the elements
element\n3.Sum of the elements\n4.Print multiple times\nEnter your 4.Print multiple times
option\n")) Enter your option
if resp==1: 1
firstele=t[0] Elements : 1 5
lastele=t[-1] Do you want to continue?(Yes/No)
print("Elements : ",firstele,lastele) Yes
elif resp==2: 1.Print first and last element
x=min(t) 2.Minimum element
print("Minimum element : ",x) 3.Sum of the elements
3
Enter the item to update :
pen
Enter the new price for the item :
40
Do you want to continue?(Yes/No)
Yes
1.Add element to the dictionary
2.Display the length of the dictionary
3.Update the element
4.Clear dictionary
5.Display items
6.Exit
Enter you choice
5
pencil - 20
pen - 40
Do you want to continue?(Yes/No)
Yes
1.Add element to the dictionary
2.Display the length of the dictionary
3.Update the element
4.Clear dictionary
5.Display items
6.Exit
Enter you choice
4
Do you want to continue?(Yes/No)
Yes
1.Add element to the dictionary
2.Display the length of the dictionary
3.Update the element
4.Clear dictionary
5.Display items
6.Exit
Enter you choice
2
Length is : 0
Do you want to continue?(Yes/No)
Yes
1.Add element to the dictionary
2.Display the length of the dictionary
3.Update the element
4.Clear dictionary
5.Display items
6.Exit
Part-A
1. What is a list?
A list is an ordered set of values, where each value is identified by an index. The values
that make up a list are called its elements. Lists are similar to strings, which are ordered
sets of characters, except that the elements of a list can have any type.
2. Relate string and list. [A.U Jan 2019]
o A string is a sequence of characters. It can be declared in python by using double
quotes. Strings are immutable, that is, they cannot be changed.
o Example:
a=“This is a string”
print a
o Lists are one of the powerful tools in python. They are just like arrays declared in
other languages, but the most powerful thing is that list need not be always
homogeneous. A single list can contain strings, integers, as well as objects. Lists
are mutable, that is, they can be altered once declared.
o Example
L=[1,a,“string”,1+2]
3. How to slice a list in python? [A.U Jan 2018]
A subset of elements of a list is called slice of a list.
Syntax: var_name=list_name[start:stop:step]
Example Explanation
>>> L1=[10,20,30,40,50] The L1[1:4] returns the subset of list starting from
>>> L1[1:4] the start index 1 to one index less than that of end
[20, 30, 40] index, i.e. 4-1=3
>>> numbers[1] = 5
List Tuples
The syntax for list The syntax for tuple:
listWeekDays=[‘mon’, ‘tue’, ‘wed’,2] tupWeekDays=(‘mon’, ‘tue’, ‘wed’,2)
List uses [and] to bind elements in the Tuple uses ( and ) to bind elements.
collection.
List is a mutable entity. You can alter list data A tuple is a list in which one cannot edit once
anytime in your program. it is created in python code. The tuple is an
immutable data structure.
Insert, pop, remove and sort elements in the list Insert, pop, remove and sort elements cannot
can be done with inbuilt function. be done. Moreover, it is immutable data type
so there is no way to change the elements in a
tuple.
19. Demonstrate with simple code to draw the histogram in python. [AU May 2019]
Part-B
1. Discuss the different options to traverse a list [AU Jan 2019] [8 Marks]
2. Demonstrate the working of +,-,* and slice operations in python [AU Jan 2019] [8
Marks]
3. Compare and contrast tuples and list in python. [4 Marks]
4. What is a dictionary python? Give example. [4 Marks]
5. Appraise the operations for dynamically manipulating dictionaries. [4 Marks]
6. Write a python program to perform linear search and binary search in a list. [16 marks]
7. Demonstrate with code the various operations that can be performed on tuples. [16
Marks] [AU May 2019]
8. Explain the various operations and methods performed using lists and sets in detail. [16
Marks]
******************************************************************************
Unit III
Control Structures
A program statement that causes a jump of control from one part of the program to another
is called control structure or control statement.
These control statements are compound statements used to alter the control flow of the
process or program depending on the state of the process.
Sequential Statement
The decision control statements usually jumps from one part of the code to another
depending in whether a particular condition is satisfied or not.
That is, they allow you to execute statements selectively based on certain decisions.
Such type of decision control statements are known as selection control statements or
conditional branching statements.
Python language supports different types of conditional branching statements which are as
follows
o Simple if statement
o if…else statement
o Nested if statement
o if-elif-else statement
Simple if statement
Syntax of if statement
if(Condition/ Test Expression): # Header
Statement 1
Statement 2
.
. Suite
.
Statement n
Statement x
If - else statement
if(condition/test expression):
statement block 1
else:
statement block 2
Statement x
Nested If statement
When a programmer writes one if statement inside another if statement then it is called a
nested if statement.
print("a is large")
else:
print("c is large")
elif(b>c):
print("b is large")
else:
print("c is large")
If-elif-else
def multiplication(a,b): 8
return a*b
def division(a,b):
return a/b
def modulo(a,b):
return a%b
def average(a,b):
return (a+b)/2
def power(a,b):
return a**b
a=int(input())
b=int(input())
select=int(input())
if select==1:
print("%d"%addition(a,b))
if select==2:
print("%d"%subtraction(a,b))
if select==3:
print("%d"%multiplication(a,b))
if select==4:
print("%.2f"%division(a,b))
if select==5:
print("%d"%modulo(a,b))
if select==6:
print("%.2f"%average(a,b))
if select==7:
print("%d"%power(a,b))
Grade Allocation Output
Program to illustrate the use of nested if statement Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
import math
a=float(input("Enter coefficients a, b and c:"))
b=float(input())
c=float(input())
D=(b*b)-(4*a*c)
if(D==0):
root1=root2=-b/(2*a)
print("root1=root2= %.2f"%root1)
elif(D>0):
root1=(-b+math.sqrt(D))/(2*a)
root2=(-b-math.sqrt(D))/(2*a)
print("root1= %.2f and root2= %.2f"%(root1,root2))
else:
D=-D
x=-b/(2*a)
y=math.sqrt(D)/(2*a)
print("root1= %.2f+%.2fi and root2= %.2f-%.2fi"%(x,y,x,y))
Program to check whether the give number is divisible by 5 or not Output
x=int(input("Enter an integer :")) Enter an integer : 25
if(x>0 and x%5==0): 25 is divisible by 5.
print(x,"is divisible by 5") Enter an integer : 23
elif(x>0 and x%5!=0): 23 is not divisible by 5
print(x,"is not divisible by 5")
else:
print(x,"is invalid")
Write a Program that prompts the user to enter a number between Output
1-7 and then displays the corresponding day of the week
num=int(input("Enter any number between 1 to 7 :")) Enter any number between 1 to 7 :5
if(num==1):print("Sunday") Thursday
elif(num==2):print("Monday")
elif(num==3):print("Tuesday")
elif(num==4):print("Wednesday")
elif(num==5):print("Thursday")
elif(num==6):print("Friday")
elif(num==7):print("Saturday")
else:
print("Wrong Input")
Iteration or loop are used in situation when the user need to execute a block of code several
of times or till the condition is satisfied.
A loop statement allows to execute a statement or group of statements multiple times.
While loop
while loop is a loop control statement in Python and frequently used in programming for
repeated execution of statement(s) in a loop
It executes the sequence of statements repeatedly as long as a condition remains true
print(sum)
Factorial of a number Output
n=int(input("Enter a number")) Enter a number5
i=1 120
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(fact)
Sum of digits of number Output
n=int(input("Enter a number")) Enter a number123
sum=0 6
while(n>0):
a=n%10
sum=sum+a
n=n//10
print(sum)
Reverse the given number Output
n=int(input("Enter a number:")) Enter a number:1234
x=n Reverse of a entered number is 4321
rem=0
while n>0:
rem=(rem*10)+n%10
n=n//10
print("Reverse of a entered number",x,"is",rem)
Armstrong Number Output
n=int(input("Enter a number")) Enter a number153
org=n The given number is Armstrong
sum=0 Number
while(n>0):
a=n%10
sum=sum+(a*a*a)
n=n//10
if(sum==org):
print("The given number is Armstrong
Number")
else:
print("The given number is not Armstrong
Number")
sum=sum+i
i=i+2
print(sum)
Newton’s Square Root Output
def newtonSqrt(n): Enter the number:
approx=0.5*n
better=0.5*(approx+n/approx) 81
while better!=approx:
approx=better The square root is 9.0
better=0.5*(approx+n/approx)
return approx
n=int(input("Enter the number"))
print("\nThe square root is",newtonSqrt(n))
for loop
for loop iterates over a sequence that may have different data types such as the list, tuple
and string.
It is also an entry check loop.
The condition is checked in the beginning and the body of the loop is executed if it is only
true otherwise the loop is not executed.
31
37
41
43
47
Printing multiplication table Output
num=int(input("enter a number:")) enter a number:5
for i in range(1,11): 5*1=5
print(num,"*",i,"=",num*i) 5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Counting number of vowels in a string Output
string=input("Enter any string:") Enter any string:programming
vowels='aeiou' {'o': 1, 'a': 1, 'u': 0, 'i': 1, 'e': 0}
string=string.casefold()
count={}.fromkeys(vowels,0)
for char in string:
if char in count:
count[char]+=1
print(count)
Generating Fibonacci Series Output
num = int(input("enter number of digits you want in enter number of digits you want in
series (minimum 2): ")) series (minimum 2): 6
first = 0 fibonacci series is:
second = 1 011235
print("\nfibonacci series is:")
print(first,end=" ")
print(second,end=" ")
for i in range(2, num):
next = first + second
print(next, end=" ")
first = second
second = next
To Print given numbers of *s in row Output
n=int(input("enter n value")) enter n value 3
for i in range(n): ***
print("*",end=" ")
Pattern Prining Problems
n=int(input("enter n value")) enter n value 4
Nested Loops
A loop placed within another loop is called as nested loop structure. One can place a while
within another while; for within another for.
Example 2 Output
for i in range(3): i=0,j=0
for j in range(2): i=0,j=1
print('i={},j={}'.format(i,j)) i=1,j=0
i=1,j=1
i=2,j=0
i=2,j=1
Example 3 Output
n=int(input("enter number of rows")) enter number of rows 4
for i in range(n): 1234
for j in range(n-i): 123
print(j+1,end=' ') 12
print() 1
break statement
continue statement
pass statement
break continue
It terminates the current loop and Skips the current iteration and also
executes the remaining statements transfer the control to the next iteration
outside the loop in the loop
Control passes to the next statement Control passes at the beginning of the
loop
Terminates the loop Never terminates the loop
Example Exanple
w w
e e
l l
o
m
e
else statement in loops
Exception Handling
The programs that we write may behave abnormally or unexpectedly because of some
errors and/ or exceptions.
The two common types of errors that we very often encounter are syntax errors and logic
errors.
While logic errors occur due to poor understanding of problem and its solution.
On other hand, syntax errors arises due to poor understanding of the language.
Exceptions are run-time anomalies or unusual conditions (such as divide by zero,
accessing arrays out of its bounds, running out of memory or disk space, overflow,
and underflow) that a program encounter during execution.
Syntax Errors
Syntax errors occurs when we violate the rules of python and they are the most common
kind of error that we get while learning a new language.
Logical Errors
Exception
Example 1 : ZeroDivisionError
a=int(input("Enter first Number"))
b=int(input("Enter second Number"))
print("The result : ",a/b)
Example 2 : FileNotFoundError
f=open("xyzxyz.txt")
print(f.read())
IOError: [Errno 2] No such file or directory: 'xyzxyz.txt'
Example 3: IndexError
lst=[1,2,3,4]
print(lst[9])
IndexError: list index out of range
Exception Description
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised where there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tab tabs and spaces.
EOFError Raised when the input () functions hits end-of-file condition.
IndexError Raised when index of a sequence is out of range.
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not foumd in local or global scope.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+ c or delete).
ImportError Raised when the imported module is not found.
OSError Raised when system operation causes system related errors.
ValueError Raised when a function gets argument of correct type but improper
value.
ZeroDivsionError Raised when second operand of division or module operation is zero.
SystemError Raised when interpreter detects internal error.
TypeError Raised when a function or operation is applied to an object of
incorrect type.
SystemExit Raised by sys.exit() function.
KeyError Raised when key is not found in dictionary.
FloatingPointError Raised when a floating point operation fails.
AttributeError Raised when attribute assignment or reference fails.
AssertionError Raised when assert statement fails.
Handling Exceptions
We can handle exceptions in our program by using try block and except block.
A critical operation which can raise exception is placed inside the try block that handles
exception is written in except block.
Python allows you to have multiple except blocks for a single try block.
The block which matches with the exception generated will get executed.
A try block can be associated with more than one except block to specify handlers for
different exceptions.
except
In the above example there is no exception so finally
except block is skipped.
In the above there is an exception in try block
so except block is executed.
One can specify an except block without mentioning any exception (i.e.except).
This type of except block if present should be the last one that can serve as a wildcard.
The statement(s) in the else block is executed only if the try clause does not raise exception.
Python allows the programmer to create their own exception by deriving classes from
the standard built-in exceptions.
These exceptions are called as user-defined exceptions (or) customized exceptions.
In try block, the user-defined exception is raised and caught in except block.
This is useful when it is necessary to provide more specific information when an
exception is caught.
Part-A
1. Write a Python Program to accept two numbers find the greatest and print the
result (AU Jan 2018)
if num1>num2:
largest=num1
else:
largest=num2
2. Present the flow of execution for a while execution. (AU Jan 2019)
3. Find the syntax error in the given code. (AU Jan 2019)
While True print(“hello world”)
Ans:
while True:
print(“hello world”)
break continue
It terminates the current loop and Skips the current iteration and also
executes the remaining statements transfer the control to the next iteration
outside the loop in the loop
Control passes to the next statement Control passes at the beginning of the
loop
Terminates the loop Never terminates the loop
Example Exanple
w w
e e
l l
o
m
e
Example:
i=1
while True:
print("Hello:",i)
i=i+1
s=input("enter a string:")
c=0
for i in s:
if i in "aeiouAEIOU":
c=c+1
s=input("enter a string:")
print(s[char],end="")
lis1=list(lis.split())
uniq_items=[]
for x in lis1:
if x not in uniq_items:
uniq_items.append(x)
print(uniq_items)
13. Write a program to perform the division of two numbers by using except clause.
try:
c=a/b
print('a = ',a)
print('b = ',b)
print('a/b = ',c)
except ZeroDivisionError:
Part-B
1. List three types of conditional statements in python and explain them. (AU Jan 2019)
2. Write a python code to perform linear search. (AU Jan 2019)
3. Appraise with an example nested if and elif header in python (AU Jan 2018)
4. Explain with an example while loop, break statement and continue statement in
python. (AU Jan 2018)
5. Write a python program to generate first ‘N’ Fibonacci series. (AU Jan 2018)
6. Write a python code for following:
a. Prime number between the given range
b. Check prime number
c. Print student grade
d. Armstrong numbers
e. Sum of even and odd numbers.
7. Explain in detail about exception handling and customized exceptions. (AU Jan
2018,2019,2020)
8. Write a python program to Count Vowels and Consonants in a String.
vowels = 0
consonants = 0
for i in str1:
vowels = vowels + 1
else:
consonants = consonants + 1
Unit IV
Modules and Packages - Variable Scope - Recursion - File Handling - Read - Write - Command
Line Programming
Modules
Module
Creating a Module [user defined]
Built-in modules
o Calendar
o Math
o Random
Randint
Using choice
Way to access the module
o Through import statement
o from…import
o import all names
Module
Example.py
def add(a,b):
result=a+b
return result
print(add(5,6))
Output:
11
Built-in Modules
Random
Math
Calendar and date-time
1. Random
Usage/Need:
If we want a computer to pick a random number in a given range we use random
function
Random Functions
Randint
o If we want a random integer, we use the randint function
o randint accepts two parameters : lowest and highest number
Example
import random
print(random.randint(0,5))
The output will be either 0, 1,2,3,4 or 5
Using Choice
o Helps to generate a random value from the sequence
o The choice function can often be used for choosing a random element from
a list
Example
import random
mylist=[2,101,False]
print(random.choice(my2list))
2. Math
The math module provides access to mathematical constants and functions
Example
import math
print(math.pi)
print(math.e)
print(math.factorial(5))
print(math.sin(2))
print(math.cos(0.5))
print(math.sqrt(49))
Output
We can import a module using import statement and access the definitions inside it using
dot operator
Example
import math
from…..import statement
Example
>>> print(pi)
3.141592653589793
>>> print(e)
2.718281828459045
Important everything with the asterisk (*) symbol is not a good programming practice.
>>> print(pi)
3.141592653589793
Packages
A package is just a way of collecting related modules together within a single tree like
hierarchy.
It has a well-organized hierarchy of directories for easier access.
A directory can contain sub-directories and files, where as a python package can have sub-
packages and modules.
Thus a package in Python is a directory which must contain a special file called _init_.py.
This file can be left empty but generally, the initialization code is placed for that package
in this file.
Creating a Package
Syntax
File Handling
File is a named location on the system storage which records data for later access
Files enable persistent storage in a non-volatile memory. i.e .Hard Disk
Python supports two types of files
o Text files
o Binary files
Text files
A file that can be processed using text editor such as notepad is called text file.
Text files are stored in a form that is human-readable.
Text files occupy more space.
Binary Files
Binary files can be handled in a manner similar to that used for text files.
Binary files contain binary data which is readable only by computer.
Access mode ‘r’ is required to open normal text files.
In order to open binary files, we should include ‘b’, i.e. ‘rb’ to read binary file and ‘wb’ to
write binary files.
Binary files don’t have text in them.
They might have pictures, music or some other kinds of data.
Binary file occupies less space the text file.
Opening a File
<FileVariableName>=open(“File Path”,<Mode>)
Or
<FileVariableName>=open(“File Path”)
Mode Description
‘r’ Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
‘w’ Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
‘a’ Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new
file for writing.
‘r+’ Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.
‘w+’ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
‘a+’ Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.
‘rb' Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
‘wb’ Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
Opens a file for both reading and writing in binary format. The file pointer placed
‘rb+’
at the beginning of the file.
Opens a file for both writing and reading in binary format. Overwrites the existing
‘wb+’
file if the file exists. If the file does not exist, creates a new file for reading and
writing.
‘ab+’ Opens a file for both appending and reading in binary format. The file pointer is at
the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
It is also able to specify to open the file in text mode or binary mode.
The default is reading in text mode.
The text mode returns strings when reading from the file.
The binary mode returns bytes and this is the mode to be used when dealing with non-text
files like image or exe files.
Example:
Closing a File
Closing a file will free up the resources that were tied with the file and is done using
close () method.
>>> f=open("d:/test.txt",'w')
>>> f.close()
Writing to a file
After execution
writelines()
o The writelines() method writes the items of a list to the file.
o Syntax: file.writelines (list)
Example
Language
Reading a file using readline () method
The readlines () method returns a list containing each line in the file as a list item.
The append ‘a’ mode of a file is used to append data to the end of an existing file.
With Statement
The user can also work with file objects using with statement.
It is designed to provide much clearer syntax and exceptions handling when you are
working with code.
Syntax
Example Output
with open("D:/test.txt") as file: I
for line in file:
print(line) Love
Python
Programming
Attributes of file object
Attribute Description
file.closed If file is closed returns true else false
file.mode Returns access mode with which file was
opened
file.name Returns name of the file.
Example
Example Output
f=open("D:/test.txt",'wb') Name of the file: D:/test.txt
print("Name of the file:",f.name) Closed or not: False
print("Closed or not:",f.closed) Opening mode: wb
print("Opening mode:",f.mode)
Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations, such
as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
It takes two arguments the current file name and new file name.
Syntax: os.rename(current_file_name, new_file_name)
You can use remove () method to delete files by supplying the name of the file to be
deleted as the argument.
Syntax: os.remove(file_name)
File Positions
tell() Method
o The tell() method returns the current file position in a file stream.
o Syntax : file.tell()
seek () method
o The seek () method sets the current file position in a file stream.
o The seek() method also returns the new position.
o Syntax : file.seek(offset)
When the program is too complex and large they are divided into parts. Each part is
separately coded and combined into single program. Each subprogram is called as function
Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
Functions are used to avoid rewriting same code again and again in a program.
Function provides code re-usability
The length of the program is reduced.
STEPS
Function definition
Function Call
Defining Function
Syntax
Function Call
Calling a function is similar to other programming languages, using the function name,
parenthesis (opening and closing) and parameter(s).
Syntax: function_name(arg1, arg2)
Flow of execution
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
Parameters
• Parameters are the value(s) provided in the parenthesis when we write function header.
Arguments
• Example: my_add(x,y)
Actual Parameters
When a function is invoked, you pass a value to the parameter. This value if referred to as
actual parameter or argument.
Formal Parameters
The variables defined in the function header are known as formal parameters.
Function Arguments
Required Arguments
The number of arguments in the function call should match exactly with the function
definition
Keyword Arguments
Keyword arguments will invoke the function after the parameters are recognized by their
parameter names.
Arguments preceded with a variable name followed by a = sign
print("Age:",age)
return
my_details(name="george",age=45)
Default Arguments
Assumes a default value if a value is not provided in the function call for that argument.
If we want to specify more arguments than specified while defining the function, variable
length arguments are used. It is denoted by * symbol before parameter.
In this type no argument is passed through the function call and no output is return to main
function
The sub function will read the input values perform the operation and print the result in the
same block
ii) Function with arguments and without return type
Arguments are passed through the function call but output is not return to the main function
In this type arguments are passed through the function call and output is return to the main
function
Anonymous Functions
Local Scope
These are the variables that are declared inside the function.
It’s lifetime and scope is within block/function only.
We cannot access this outside the function block.
If we try to access those variables then error will show by interpreter.
Global Scope
Recursion
It is a process of calling the same/own function itself again and again until some condition
is satisfied.
A base condition is must in every recursive function otherwise it will continue to execute
like an infinite loop.
Advantages
o Recursive functions make the code look clean end elegant.
o A complex task can be broken down into simpler sub-problems using recursion.
Limitations
o Every time function calls itself and stores some memory. Thus, a recursive function
could hold much more memory than traditional function.
Example Programs
else:
return n*fact(n-1)
n=int(input("Enter a number:"))
result=fact(n)
print("Factorial of",n,"is",result)
GCD of two numbers Output
def ComputeGCD(a,b): Enter the first number:64
if b==0: Enter the second number:48
return a 16
else:
return ComputeGCD(b,a%b)
num1=int(input("Enter the first number:"))
num2=int(input("Enter the second number:"))
print(ComputeGCD(num1,num2))
Fibonacci Series using Recursion Output
def fib(n): Enter the value of n
if n==1: 4
return 0 The term 4 in the fibonocci series is 2
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
x=int(input("Enter the value of n\n"))
print("The term", x, "in the fibonocci series is",fib(x))
STEPS:
Write a program
Worked Examples
for i in range(0,n): 3
element=int(input()) Sample Output 1:
a.append(element) 16
b=sum_arr(a,n)
print(b)
Unit-IV
Part-A
1. Define file
A file is a sequence of characters stored on a permanent medium like hard drive, flash
memory or CD-ROM.
Python supports two types of files
o Text files
o Binary files
2. What are modules?
Modules are a file containing python statements and definition.
We use modules to break down large programs into small manageable and
organized files
Modules provide reusability of code
Mode Description
‘r’ Opens a file for reading
‘w’ Opens a file for writing only. Overwrite the file if
the file exists.
‘a’ Opens a file for appending data from the end of
the file.
‘wb’ Opens a file for writing binary data.
‘rb’ Opens a file for reading binary data.
r+ Opens a file for both reading and writing
9. Write a Python Program to Count the Number of Blank Spaces in a Text File
fname = input("Enter file name: ")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print("Occurrences of blank spaces:")
print(k)
10. Write a python code to copy the content from one file to another
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
11. Define recursion with its advantages and disadvantages
It is a process of calling the same/own function itself again and again until some
condition is satisfied.
A base condition is must in every recursive function otherwise it will continue to
execute like an infinite loop.
Advantages
a. Recursive functions make the code look clean end elegant.
b. A complex task can be broken down into simpler sub-problems using recursion.
Limitations
c. Every time function calls itself and stores some memory. Thus, a recursive function
could hold much more memory than traditional function.
12. Write a python program to find the factorial of a given number using recursive
functions.
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
n=int(input("Enter a number:"))
result=fact(n)
print("Factorial of",n,"is",result)
14. Write the functions for accessing and manipulating files and directories on a disk
Attribute Description
file.closed If file is closed returns true else false
file.mode Returns access mode with which file was
opened
file.name Returns name of the file.
Part-B
1. Tabulate the various modes of opening a file and explain the same [AU Jan 2018]
2. Explain the commands used to read and write into the file with example. [AU Jan 2019]
3. Write a python code to count number of word in a file. [AU April 2019]
4. Outline function definition and function call with an example [AU April 2019]
5. Write a python program to find the factorial of a number without recursion and with
recursion. [AU Jan 2018]
6. Explain in detail about modules and packages in python with examples.
Unit V
Like other general purpose languages, python is also an object-oriented language since its
beginning.
It allows us to develop applications using an Object Oriented approach. In Python, we
can easily create and use classes and objects.
Major principles of object-oriented programming system are given below.
o Object
o Class
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Object
o The object is an entity that has state and behavior. It may be any real-world object
like the mouse, keyboard, chair, table, pen, etc.
Class
o The class can be defined as a collection of objects.
o It is a logical entity that has some specific attributes and methods.
o For example: if you have an employee class then it should contain an attribute and
method, i.e. an email id, name, age, salary, etc.
o Syntax:
1. class ClassName:
2. <statement-1>
3. .
4. .
5. <statement-N>
Inheritance
o Inheritance is the most important aspect of object-oriented programming which
simulates the real world concept of inheritance.
o It specifies that the child object acquires all the properties and behaviors of the
parent object.
o By using inheritance, we can create a class which uses all the properties and
behavior of another class.
o The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
o It provides re-usability of the code.
Encapsulation
o Encapsulation is also an important aspect of object-oriented programming.
o It is used to restrict access to methods and variables.
o In encapsulation, code and data are wrapped together within a single unit from
being modified by accident.
Data Abstraction
o Abstraction means hiding the complexity and only showing the essential features
of the object.
o So in a way, Abstraction means hiding the real implementation and we, as a user,
knowing only how to use it.
o A TV set where we enjoy programs without knowing the inner details of how TV
works.
Custom Classes
Defining Classes
o In Python, a class is defined by using the keyword class. Every class has a unique
name followed by a colon (: ).
Explanation:
In the above code, the name of the class is Sample. Inside the class, we have assigned the
variables x and y with initial value 10 and 20 respectively. These two variables are called as
class variables or member variables of the class. In class instantiation process, we have created
an object S to access the members of the class. The first two print statements simply print the
value of class variable x and y and the last print statement add the two values and print the
result.
Class Methods
o Python class function or Method is very similar to ordinary function with a small
difference that, the class method must have the first argument named as self.
o No need to pass a value for this argument when we call the method.
o Python provides its value automatically.
o Even if a method takes no arguments, it should be defined with the first argument
called self.
o If a method is defined to accept only one argument it will take it as two arguments
i.e. self and the defined argument.
Constructor is the special function that is automatically executed when an object of a class
is created.
In Python, there is a special function called “init” which act as a Constructor.
It must begin and end with double underscore.
This function will act as an ordinary function; but only difference is, it is executed
automatically when the object is created.
Destructor is also a special method gets executed automatically when an object exit from
the scope.
It is just opposite to constructor. In Python, __del__ ( ) method is used as destructor.
def __del__(self):
print('Destructor called, vehicle deleted.')
car = Vehicle()
print('Hello world')
return Circle.pi*(self.radius**2)
def circumference(self):
return 2*Circle.pi*self.radius
r=int(input("Enter Radius: "))
C=Circle(r)
print("The Area =",C.area())
print("The Circumference =", C.circumference())
Attributes of a class are function objects that define corresponding methods of its instances.
They are used to implement access controls of the classes.
Attributes of a class can also be accessed using the following built-in methods and
functions.
o getattr () – This function is used to access the attribute of object.
o hasattr() – This function is used to check if an attribute exist or not.
o setattr() – This function is used to set an attribute. If the attribute does not exist,
then it would be created.
o delattr() – This function is used to delete an attribute. If you are accessing the
attribute after deleting it raises error “class has no attribute”
# sets an attribute
setattr(e1,'height',152)
delattr(emp,'salary')
Inheritance in Python
Syntax:
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.
1. class derived-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multi-level Inheritance
4. Hierarchical Inheritance
Single Inheritance
When a child class inherits from only one parent class, it is called as single inheritance.
Multiple Inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
<class-suite>
Multi-level Inheritance
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
d.speak()
d.eat()
Hierarchical inheritance
When more than one derived classes are created from a single base – it is called hierarchical
inheritance.
The issubclass(sub, sup) method is used to check the relationships between the specified
classes.
It returns true if the first class is the subclass of the second class, and false otherwise.
Example Output
class Calculation1: True
def Summation(self,a,b): False
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
The isinstance () method is used to check the relationship between the objects and classes.
It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e.,
class.
Example Output
class Calculation1: True
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Polymorphism in Python
There are some functions in Python which are compatible to run with multiple data types.
One such function is the len () function. It can run with many data types in Python. Let's
look at some example use cases of the function.
print(len("Programiz")) 9
print(len(["Python", "Java", "C"])) 3
print(len({"Name": "John", "Address": "Nepal"})) 2
Polymorphism Example
Example Output
class dog: meow
def sound(self): bow bow
print("bow bow")
class cat:
def sound(self):
print("meow")
def makesound(animaltype):
animaltype.sound()
catobj=cat()
dogobj=dog()
makesound(catobj)
makesound(dogobj)
When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding.
Example 1 Output
1. class Animal: Barking
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. d.speak()
9. Example 2 Output
1. class Bank: Bank Rate of interest: 10
2. def getroi(self): SBI Rate of interest: 7
3. return 10; ICICI Rate of interest: 8
4. class SBI(Bank):
5. def getroi(self):
6. return 7;
7.
8. class ICICI(Bank):
9. def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());
Debugging in python
While developing an application or exploring some features of a language, one might need
to debug the code anytime.
Therefore, having an idea of debugging the code is quite necessary. Let’s see some basics
of debugging using built-in function breakpoint () and pdb module.
We know that debugger plays an important role when we want to find a bug in a particular
line of code. Here, Python comes with the latest built-in function breakpoint which do the
same thing as pdb.set_trace() in Python 3.6 and below versions.
Syntax:
In this method, we simply introduce the breakpoint where you have doubt or somewhere
you want to check for bugs or errors.
Example Output
def debugger(a, b):
breakpoint()
result = a / b
return result
print(debugger(5, 0))
In order to run the debugger just type c and press enter.
To use the PDB in the program we have to use one of its method named set_trace ().
Although this will result the same but this the way to introduce the debugger in python
version 3.6 and below.
Example Output
def debugger(a, b):
import pdb; pdb.set_trace()
result = a / b
return result
print(debugger(5, 0))
Testing in Python
Types of Testing
o Unit Testing
o Integration Testing
Unit Testing
o The process of testing whether a particular unit is working properly or not is called
unit testing
Integration Testing
o The process of testing total application (end-to-end testing)
o Quality Assurance team is responsible for Integration Testing
Test fixture
o A test fixture is used as a baseline for running tests to ensure that there is a fixed
environment in which tests are run so that results are repeatable.
o Examples :
Creating temporary databases.
Starting a server process.
Test case
o A test case is a set of conditions which is used to determine whether a system
under test works correctly.
Test suite
o Test suite is a collection of testcases that are used to test a software program to
show that it has some specified set of behaviours by executing the aggregated
tests together.
How to perform Unit Testing in Python
o Module name: unittest
o Class name: TestCase
o Instance methods: 3 methods
setUp()
Method called to prepare the test fixture.
This is called immediately before calling the test method
test()
teardown()
Method called immediately after the test method has been called
and the result recorded.
def tearDown(self):
print("tearDown method execution..")
Example 1 Output
import unittest setUp method execution...
class TestCaseDemo(unittest.TestCase): test method execution..
def setUp(self): tearDown method execution..
print("setUp method execution...") .
def test_method1(self): -------------------------------------------
print("test method execution..") ---------------------------
def tearDown(self): Ran 1 test in 0.008s
print("tearDown method execution..")
unittest.main() OK
Outcomes Possible:
Example 2 Output
import unittest -------------------------------------------
class TestCaseDemo(unittest.TestCase): ---------------------------
def setUp(self): Ran 1 test in 0.016s
print("setUp method execution...")
def test_method1(self): FAILED (errors=1)
print("test method execution..")
print(10/0)
def tearDown(self):
print("tearDown method execution..")
unittest.main()
Profiling in Python
Using Timers
Timers are easy to implement and they can be used anywhere at a program to measure the
execution time.
By using timers we can get the exact time and we can improve the program where it takes
too long.
Time module provides the methods in order to profile a program.
Example 1 Output
# importing time module Time Consumed
import time 0.01517796516418457 seconds
start = time.time()
print("Time Consumed")
print("% s seconds" % (time.time() - start))
Example 2 Output
import time Time consumed
gfg() function takes
def gfg(): 0.015180110931396484 seconds
start = time.time()
print("Time consumed")
end = time.time()
print("gfg() function takes", end-start, "seconds")
# Calling gfg
gfg()
Using line_profiler:
Python provides a built-in module to measure execution time and the module name is
LineProfiler.
It gives detailed report on time consumed by a program.
Example 1 Output
# importing line_profiler module Timer unit: 4.27198e-10 s
from line_profiler import LineProfiler
def geek(rk):
print(rk)
rk ="geeks"
profile = LineProfiler(geek(rk))
profile.print_stats()
Using cProfile:
Python includes a built in module called cProfile which is used to measure the execution
time of a program.
cProfiler module provides all information about how long the program is executing and
how many times the function get called in a program.
Example 1 Output
# importing cProfile 3 function calls in 0.000 seconds
import cProfile
cProfile.run("10 + 10")
Part-A
Part-B
1. Explain the different types of inheritance in python with necessary example programs
2. i) Write a python program to demonstrate the working of classes and objects with an
example program
ii) Explain the various object oriented terminologies
3. Discuss about polymorphism concept and method overriding with suitable examples
4. Discuss testing, profiling and debugging in python with example programs.