Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PYTHON Complete Notes With QB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 165

Sri Eshwar College of Engineering (An Autonomous Institution)

Coimbatore- 641 202

Unit I

BASICS OF PYTHON PROGRAMMING

Introduction to Python - Python Interpreter - Data types - Identifiers and keywords - Integral Types
- Floating Point Types – Strings

Introduction to 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.

Features of Python

a) General purpose language


 It can be used to write code for any task.
 Nowadays, it is used in Google, NASA, and New York stock exchange.
b) Easy-to-Learn
 A Python program is clearly defined and easily readable.
 The structure of the program is very simple.
 It uses few keywords and clearly defined syntax.
 This makes it easy for just anyone to pick up the language quickly.
c) High-level language
 When writing programs in python, the programmers don’t have to worry about
the low-level details like memory used by the program, etc.
 They just need to concentrate on solutions of the current problem at hand.
d) Interactive
 Programs in python work in interactive mode which allows interactive
debugging and testing of pieces of code.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 1


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 2


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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

 There are two ways to use the interpreter


o Interactive mode
o Script mode
 Interactive mode
o In interactive mode python code can be directly typed and the interpreter displays
the result(s) immediately.
o It is a command shell which give immediate feedback for each statement.
o Working in interactive mode is convenient for beginners and for testing small
pieces of code
o The following command can be used to invoke Python IDLE from Windows OS.
Start → All Programs → Python 3.x → IDLE (Python 3.x)

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 3


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 4


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 Creating Scripts in Python


1. Choose File → New File or press Ctrl + N in Python shell window.

2. An untitled blank script text editor will be displayed on screen as shown below

3. Type the following code in Script editor

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 5


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

a =100

b = 350

c = a+b

print ("The Sum=", c)

4. Save the file using File-


>Save->Filename.py

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 6


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

5. Run the code by pressing F5.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 7


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Differences between Interactive mode and Script mode

Interactive mode Script mode


 A way of using the Python interpreter  A way of using the Python interpreter
by typing commands and expressions to read and execute statements in a
at the prompt script
 Can’t save and edit the code  Can save and edit the code
 We can see the results immediately  We cannot see the results immediately

Comments in Python

 A comment statement contains information for persons reading the program.


 Comment statements are non-executable statements so they are ignored during
program execution.
 They have no effect on the program results.
 In python comments begin with hash symbol (#).
 The lines that begins with # symbol are considered as comments and ignored by the python
interpreter.

#swap.py
#Swapping the values of two variable program
#written by V.Balamurugan, April 2019

 Another way of comments is to use triple quotes ''' or """

"""swap.py
Swapping the values of two variable program
written by V.Balamurugan, April 2019"""

Input and Output Functions

 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)

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 8


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

print(“String to be displayed as output”, variable)


print (“String1 ”, variable, “String 2”, variable, “String 3” ……)
o Example

>>> print("Welcome to Python Programming")


Welcome to Python Programming
>>> x=5
>>> y=6
>>> z=x+y
>>> print(z)
11
>>> print("The sum=",z)
The sum= 11
>>> print("The sum of",x,"and",y,"is",z)
The sum of 5 and 6 is 11

 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().

Variable = input (“prompt string”)


o Example
>>>x=input(“Enter the name:”)
Enter the name: bala
>>>y=int(input(“Enter the number”))
Enter the number 3
o Note: Python accepts string as default type. Conversion is required for type.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 9


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 The eval() FUNCTION


o The full form of eval function is to evaluate.
o It takes string as a parameter and returns it as if it is a python expression.
o The eval function takes a string and returns it in the type it is expected. The
following example illustrates this concept
o Example
>>> X=eval('123')
>>> X
123
>>> type(X)
<class 'int'>
o By making use of eval () function, we can avoid specifying a particular type in
front of input () function.

Program to Demonstrate the use of eval Output


function
Name=(input('Enter Name:')) Enter Name:Donald Trump
Age=eval(input('Enter Age:')) Enter Age:60
Gender=(input('Enter gender:')) Enter gender:M
Height=eval(input('Enter Height:')) Enter Height:5.6
print('User Details are as follows:') User Details are as follows:
print('Name :',Name) Name : Donald Trump
print('Age:',Age) Age: 60
print('Gender:',Gender) Gender: M
print('Height:',Height) Height: 5.6
print(type(Age)) <class 'int'>
Indentation

 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")

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 10


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Variable and Identifiers

 Variables in simple language, means its value can vary.


 Variables are noting but just parts of computer’s memory where information is stored.
 To be identified easily, each variable is given an appropriate name.
 Variables are examples of identifiers.
 An Identifier is a name used to identify a variable, function, class, module or object.
 Rules
o An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
o Identifiers may contain digits (0 .. 9), but cannot start with a digit.
o Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct
o Identifiers must not be a python keyword.
o Python does not allow punctuation character such as %,$, @ etc., within identifiers.
 Example of valid identifiers
o Sum, total_marks, regno, num1
 Example of invalid identifiers
o 12Name, name$, total-mark, continue
 Assigning a value to a variable
o In Python, the equal sign (=) is used as the assignment operator
o Syntax : Variable=expression

Keywords

 Keywords are the reserved words in Python.


 Keywords are case sensitive.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 11


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 12


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

# Demo Program to test Arithmetic Operators Output


a=100 The Sum = 110
b=10 The Difference = 90
print ("The Sum = ",a+b) The Product = 1000
print ("The Difference = ",a-b) The Quotient = 10.0
print ("The Product = ",a*b) The Remainder = 10
print ("The Quotient = ",a/b) The Exponent = 10000
print ("The Remainder = ",a%30) The Floor Division = 3
print ("The Exponent = ",a**2)
print ("The Floor Division =",a//30)

 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.

# Demo Program to test Relational Operators Output


a=int (input("Enter a Value for A:")) Enter a Value for A:35
b=int (input("Enter a Value for B:")) Enter a Value for B:36
print ("A = ",a," and B = ",b) A = 35 and B = 36
print ("The a= =b = ",a= =b) The a= =b = False
print ("The a > b = ",a>b) The a > b = False
print ("The a < b = ",a<b) The a < b = True
print ("The a >= b = ",a>=b) The a >= b = False
print ("The a <= b = ",a<=0) The a <= b = False
print ("The a != b = ",a!=b) The a != b = True

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 13


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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.

# Demo Program to test Logical Operators Output


a=int (input("Enter a Value for A:")) Enter a Value for A:50
b=int (input("Enter a Value for B:")) Enter a Value for B:40
print ("A = ",a, " and b = ",b) A = 50 and b = 40
print ("The a > b or a == b = ",a>b or a==b) The a > b or a == b = True
print ("The a > b and a == b = ",a>b and a==b) The a > b and a == b = False
print ("The not a > b = ",not a>b) The not a > b = False

 Assignment Operators
o In Python, = is a simple assignment operator to assign values to variable.

Operator Name Example Equivalent to

= Equal to X=10 X=10

+= Plus Equal to X+=10 X=X+10

-= Minus Equal to X-=10 X=X-10

/= Division Equal to X/=10 X=X/10

%= Modulus Equal to X%=10 X=X%10

//= Floor equal to X//=10 X=X//10

**= Exponent Equal to X**=10 X=X**10

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 14


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

= Equal to X=10 X=10

# Demo Program to test Assignment Operators Output


x=int (input("Type a Value for X : ")) Type a Value for X : 10
print ("X = ",x) X = 10
print ("The x is =",x) The x is = 10
x+=20 The x += 20 is = 30
print ("The x += 20 is =",x) The x -= 5 is = 25
x-=5 The x *= 5 is = 125
print ("The x -= 5 is = ",x) The x /= 2 is = 62.5
x*=5 The x %= 3 is = 2.5
print ("The x *= 5 is = ",x) The x **= 2 is = 6.25
x/=2 The x //= 3 is = 2.0
print ("The x /= 2 is = ",x)
x%=3
print ("The x %= 3 is = ",x)
x**=2
print ("The x **= 2 is = ",x)
x//=3
print ("The x //= 3 is = ",x)

 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,

 Variable Name = [on_true] if [Test expression] else [on_false]


Example :
min= 50 if 49<50 else 70 # min = 50
min= 50 if 49>50 else 70 # min = 70

 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.

Operator Example Explanation


in x in y True if the value or variable
found in sequence
not in x not in y True if the value or variable
not found in sequence

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 15


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

# Demo Program to test Membership Operators Output


x="Python Program" True
print('y' in x) False
print('p' in x) True
print('hello' not in x) False
print('n' not in x)
 Identity Operators
 Identity Operators compare the memory location of two objects.
 The two identity operators are is and is not.

Operator Meaning Example


is True if the operators are identical x is true
is not True if operators are not identical x is not true

# Demo Program to test Identity Operators Output


x1 = 5 False
y1= 5 True
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
 Bitwise Operators
o Bitwise operations manipulate on bits
o Here numbers are represented with bits, a series of zeros and ones

Operator Name Example Explanation

& Bitwise AND X&Y Both operands are true result is true

| Bitwise OR X|Y True if either of the operand is true

` Bitwise NOT `x It complements the bits

^ Bitwise XOR X^Y Result is true if either of the


operands are true

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 16


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

>> Bitwise right shift X>>2 Operands are shifted right by


number of times specified

<< Bitwise left shift X<<2 Operands are shifted left by number
of times specified

# Demo Program to test Bitwise Operators Output


a=4 0
b=3 7
c=a&b 7
print(c) 16
c=a|b 1
print(c) -5
c=a^b
print(c)
c=a<<2
print(c)
c=a>>2
print(c)
c=~a
print(c)
Operator Precedence

Operator Description

** Exponentiation (raise to the power)

Complement, unary plus and minus (method


~+-
names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 17


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

 The acronym PEMDAS ( Parentheses, Exponentiation, Multiplication ,Division, Addition,


Subtraction) is a useful way to remember the rules:
o Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1) is 4, and (1+1) ** (5-2) is 8.
o Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and
2*3**2 is 18, not 36.
o Multiplication and Division have higher precedence than Addition and Subtraction.
So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5
o Operators with the same precedence are evaluated from left to right (except
exponentiation)

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 18


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Python Delimiters

 Python uses the symbols and symbol combinations as delimiters in expressions, lists,
dictionaries and strings. Following are the delimiters.

Python Literals

 A literal is a notation that represents a fixed value


 Numeric Literals
o They consist of digits (0-9) with an optional (+ or -) possibly decimal point.
o Examples of Integer Literals are:
10 3500 -4500 +220
o Floating point literals are
10.0 3500.253 -4500.232 +220.034
o Python uses double precision floating point representation format as per IEEE
754 with a range of 10-308 to 10308
o It uses a precision of 53 bits to store floating point values internally.
 Arithmetic overflow Problem
o A condition occurs when a computation produces a result that is greater that a
data type variable can store.

# Demo Program to test Arithmetic overflow error Output


a=1.4e200 inf
b=2.1e200
c=a*b
print(c)

 Arithmetic Underflow Problem


o Arithmetic underflow occurs when the result is too small in magnitude to be
represented. It occurs due to division of two long floating point numbers.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 19


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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.
 String Literals
o They represent group of characters
o They may be enclosed in a single quote or double quote, ‘Hello World!’ or
“Hello World!”

# Demo Program to represent string literals Output


str1='I am single quote' I am single quote
str2="I am double quote" I am double quote
str3="""I am triple quote I am triple quote
I am multiline quote I am multiline quote
"""
print(str1,"\n",str2,"\n",str3)

Python Data types

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

 Data types are the classification or categorization of data items.


 It represents the kind of value that tells what operations can be performed on a particular
data.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 20


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 21


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

>> 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: Range of an integer in Python can be from -2147483648 to


2147483647, and long has unlimited range subject to available
memory

Floating Point Type

 A floating point (float) type represents numbers with fractional part.


 A floating point number has a decimal point and a fractional part.
 Example: 3.0 or 3.17 or -28.72
 Python cannot represent very large or very small numbers, and the precision is limited to
only about 14 digits.
 Alternatively, floats may be expressed in scientific notation using letter “e” to indicate 10th
power.
 Example: 1.6E3 stands for 1.6 ×103 is same as 1600.0

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

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 22


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

14.0
>>> print(z)
(5+14j)
>>> print((2+3j)*(4+5j))
(-7+22j)

String Type

 A string represents sequence of characters


 It can be created using Single Quotes, Double Quotes and triple quotes
 Example

o Using Single Quotes: ‘HELLO’

o Using Double Quotes: “HELLO”

o Using Triple Quotes : ‘‘‘ Hello Every One

Welcome to Python Programming’’’


 Indexing

o Positive indexing helps in accessing the string from the beginning


o Negative subscript helps in accessing the string from end
o A[0] or A[-5] will display ‘H’
o A[1] or A[-4] will display “E”
 Operations on string
o Indexing
o Slicing
o Concatenation
o Repetitions
o Membership

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 23


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

String Operation Example Explanation


Indexing >>> s="good morning"  Accessing the elements by
>>> print(s[2]) specifying the position
o
>>> print(s[6])
o
Slicing( ending position -1) >>> print(s[2:])  Displaying items from 2nd
od morning till last.
>>> print(s[:4])  Displaying items from 1st
good position till 3rd .
Concatenation >>> print(s+"friends")  Adding and printing the
good morningfriends characters of two strings.
Repetition >>> print(s*2)  Creates new strings by
good morninggood morning concatenating multiple
copies of the same string
in, not in(membership >>> "m" in s  Using membership
operator) True operators to check a
>>> "a" in s particular character is in
False string or not. Returns true
if present.

Boolean Type

 A Boolean type represents special values ‘True’ and ‘False’


 They are represented as 1 and 0
 The most common way to produce a Boolean value is with a relational operator

Example: 2<3 is True

List Type

 List is an ordered sequence of items

 Values in the list are called elements/items

 Lists are created by placing all items inside a square bracket separated by commas

 Items in a list can be of different data type

 Lists are mutable

Operations on List

 Indexing

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 24


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 Slicing

 Concatenation

 Repetitions

 Updation, Insertion and Deletion

List Operations Example Explanation


Creating a list >>>list1=["python",7.79,101,"hello"]  Creating the list with
>>> list2=["god",6.78,9] elements of different data
types.
Indexing >>> print(list1[0])  Accessing the item in the
python position 0
>>> list1[2]  Accessing the item in the
101 position 2
Slicing( ending >>> print(list1[1:3])  Displaying items from 1st
position -1) [7.79, 101] till 2nd.
Slice operator is >>> print(list1[1:])  Displaying items from 1st
used to extract part [7.79, 101, 'hello'] position till last.
of a string, or
some part of a list
in Python
Concatenation >>> print(list1+list2)  Adding and printing the
['python', 7.79, 101, 'hello', 'god', items of two lists.
6.78, 9]
Repetition >>> list2*3  Creates new list by
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating multiple
6.78, 9] copies of the same list
Updating the list >>> list1[2]=45  Updating the list using
>>> print(list1) index value
['python', 7.79, 45, 'hello']
Inserting an >>> list1.insert(2,"program")  Inserting an element in
element >>> print(list1) 2nd position
['python', 7.79, 'program', 45, 'hello']
Removing an >>> list1.remove(45)  Removing an element by
element >>> print(list1) giving the element
['python', 7.79, 'program', 'hello'] directly

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.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 25


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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

Tuple Operations Example Explanation


Creating a tuple >>> t=("python",7.79,101,"hello")  Creating the tuple with elements
of different data types.
Indexing >>> print(t[0])  Accessing the item in the
python position 0
>>> t[2]  Accessing the item in the
101 position 2
Slicing( ending >>> print(t[1:3])  Displaying items from 1 st till
position -1) (7.79, 101) 2nd.
Slice operator is used to
extract part of a string, or
some part of a list
Python
Concatenation >>> t+("ram",67)  Adding tuple elements at the end
('python', 7.79, 101, 'hello', 'ram', of another tuple elements
67)
Repetition print(t*2)  Creates new strings,
('python', 7.79, 101, 'hello', concatenating multiple copies of
'python', 7.79, 101, 'hello') the same string

Note: Altering the tuple data type leads to error.

>>> t[0]='a'

Traceback (most recent call last):

File "<pyshell#8>", line 1, in <module>

t[0]='a'

TypeError: 'tuple' object does not support item assignment

Mapping

 This data type is unordered and mutable


 Example: Dictionaries

Dictionaries

 Lists are ordered sets of objects, whereas dictionaries are unordered sets.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 26


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 Dictionary is created by using curly brackets. i,e. {}


 Dictionaries are accessed via keys and not via their position.
 The values of a dictionary can be any Python data type. So dictionaries are unordered key-
value-pairs(The association of a key and a value is called a key-value pair )
 Syntax for creating dictionary
o dict_sample={key 1:value 1,key 2:value 2,…….key n:value n}

Dictionary Operations Example Explanation


Creating a Dictionary >>> food={1:'a',2:'b',3:'c',4:'d',5:'e'}  Creating the dictionary with
elements of different data types.
Indexing >>> print(food[1])  Accessing the item with keys.
a

Tuple Assignment

 An assignment to all of the elements in a tuple using single assignment statement


 The left side is a tuple of variables; the right side is a tuple of values.
 Naturally, the number of variables on the left and the number of variables on the right have to
be the same

Example:

>>> T1=(10,20,30)

>>> T2=(100,200,300,400)

>>> print(T1)

(10, 20, 30)

>>> print(T2)

(100, 200, 300, 400)

>>> T1,T2=T2,T1

>>> print(T1)

(100, 200, 300, 400)

>>> print(T2)

(10, 20, 30)

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 27


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

 An individual character in string is accessed using an index


 Strings are immutable i.e. the contents of the string cannot be changed after it is created.
 The index should always be an integer (positive or negative)
 Positive subscript helps in accessing the string from beginning.
 Negative subscript helps in accessing the string from the end.

Index from Left 0 1 2 3 4 5 6 7


Character C o m p u t e r
Index from right -8 -7 -6 -5 -4 -3 -2 -1

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.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 28


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Indexing >>> a="HELLO"  Positive indexing helps in


>>> print(a[0]) accessing the string from the
H beginning
>>> print(a[-1])  Negative subscript helps in
O accessing the string from the end
Concatenation >>> a="save"  The concatenation operator + is
>>> b="earth" used to join two strings
>>> print(a+b)
saveearth
Repetition >>> a="eshwar"  The multiplication operator (*)
>>> print(5*a) is used to concatenate the same
eshwareshwareshwareshwareshwar string multiple times
Membership s1="Information  Membership operators are used
Technology" to test whether a particular
>>> "Technology" in s1 character is in string or not. It
True returns true if present
>>> "Technology" not in
s1
False
Slicing >>> print(a[0:4])  The Slice [start:stop] operator
hell extracts sub string from the
>>> print(a[:3]) strings
hel  A segment of a string is called
>>> print(a[0:]) slice.
hello

String Slices

 A slicing operation is used to return/select/slice the particular substring based on user


requirements.
 A segment of the string is called slice.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 29


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Syntax: string_variable_name [start: end: step]

Examples for Slice Operations

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

>>> S[-1:0:-1] Access the characters of a string from index -1


'SARDAM-TI'
>>> S[:-1] Exclude the last character stored at -1
'IIT-MADRA'

Format method

 The format () method is an extremely convenient way to format text.


 Syntax: format (value, format_specifier)
o Where value is string to be displayed
o format_specifier is the combination of formatting options

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 ’

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 30


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Escape sequences

>>> print('What's your name?')

SyntaxError: invalid syntax

 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

Escape Sequences Purpose


\\ Prints Backslash
\’ Prints single-quote
\“ Prints double quote
\n Prints new line character
\t Prints a tab
\o Prints octal value
\x Prints hex value

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

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 31


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Traversal using for 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

 The len () function calculates the length of the string


 On entering the while loop, the interpreter checks the condition
 If the condition is true, it enters the loop
 The first character of the string is displayed
 The value of i is incremented by 1

String built in functions and methods

 Syntax: Stringname.method()

a=“happy birthday”

Here a is the string name

S.No Syntax Example Description


1. a.capitalize() >>> a.capitalize() Capitalize only the first letter in a
'Happy birthday' string
2. a.upper() >>> a.upper() Changes the string to upper case
'HAPPY BIRTHDAY'
3. a.lower() >>> a.lower() Changes the string to lower case
'happy birthday'
4. a.title() >>> a.title() Changes the string to title case i.e. first
'Happy Birthday' characters of all the words are
capitalized.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 32


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

5. a.swapcase() >>> a.swapcase() Change the lowercase characters to


'HAPPY BIRTHDAY' uppercase and vice versa
6. a.split() >>> a.split() The split () method returns a list of all
['happy', 'birthday'] words in a string. It is used to break up
a string into smaller strings.
7. a.center(width,“fillchar”) >>> a.center(19,'*') Pads the string with the specified
'***happy birthday** “fillchar” till the length is equal to
“width”
8. a.count(substring) >>> a.count('happy') Returns the number of occurrences of
1 substring
9. a.replace(old,new) >>> Replaces all old substrings with new
a.replace('happy','wishyou substrings
happy')
'wishyou happy birthday'
10. a.isupper() >>> a.isupper() Returns True if all characters in the
False string are in uppercase
11. a.islower() >>> a.islower() Returns True if all characters in the
True string are in lowercase
12. a.isalpha() >>> a.isalpha() Returns True if the characters in the
False string are alphabetic and there is at
least one character
13. a.isalnum() >>> a.isalnum() Checks whether the string consists of
False alphanumeric characters.
14. a.isdigit() >>> a.isdigit() Checks whether the string consists of
False digits only.
15. a.isspace() >>> a.isspace() Checks whether the string consists of
False whitespace only.
16. a.startswith(substring) >>> a.startswith("h") checks whether string starts with
True substring
17. a.endswith(substring) >>> a.endswith("y") checks whether the string ends with
True the substring
18. a.find(substring) >>> a.find('happy') Returns index of substring, if it is
0 found. Otherwise -1 is returned.
19. len(a) >>> len(a) Return the length of the string
14
20. min(a) >>> min(a) Return the minimum character in the
'' string based on their ASCII values
21. max(a) >>> max(a) Return the maximum character in the
'y' string based on their ASCII values
22. a.join(b) >>> b="happy" It is just opposite of split. The function
>>> a="-" joins list of strings using delimiter
>>> a.join(b) with which the function is invoked
'h-a-p-p-y'

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 33


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Worked Examples

Python Program to find the distance between two Output


points
x1=int(input("Enter X1:")) Enter X1:4
y1=int(input("Enter y1:")) Enter y1:0
x2=int(input("Enter X2:")) Enter X2:6
y2=int(input("Enter Y2:")) Enter Y2:6
p=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1) The distance between two points is
d=p**0.5 6.32
print("The distance between two points is %.2f"%d)
Write a Python program to find the remainder of Output
a/b, without using % operator.
x=int(input("Enter the value of a :\n")) Enter the value of a :
y=int(input("Enter the value of b :\n")) 11
q=x//y Enter the value of b :
r=x-(y*q); 2
print("Remainder is",r) Remainder is 1
Write a python program to find the area of a circle. Output

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

Simple Interest is 7000.00


Swapping of two numbers using temporary variable Output
x=int(input('Enter value of x:')) Enter value of x:34
y=int(input('Enter value of y:')) Enter value of y:67
temp=x The value of x after swapping: 67
x=y The value of y after swapping: 34
y=temp

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 34


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

print('The value of x after swapping:',x)


print('The value of y after swapping:',y)
Swapping of two numbers without using temporary Output
variable
n1=int(input('Enter value of n1:')) Enter value of n1:78
n2=int(input('Enter value of n2:')) Enter value of n2:34
n2=n1+n2 The value of x after swapping: 34
n1=n2-n1 The value of y after swapping: 78
n2=n2-n1
print('The value of x after swapping:',n1)
print('The value of y after swapping:',n2)

Finding Square root of a number Output


num=int(input("enter a number")) enter a number10
number=float(num) The square root of 10 is 3.16
sq=number**0.5
print('The square root of %d is %.2f'%(num,sq))
Write a python program string concatenation & Output
repetition
string1=input("Enter string1:") Enter string1:python
string2=input("Enter string2:") Enter string2:programming
string3=string1+string2 The concatenated string is
print('The concatenated string is %s'%string3) pythonprogramming
reptition=string1*3 The string after
print('The string after repetition%s'%reptition) repetitionpythonpythonpython
String Palindrome Output
string = input("Please enter your own String : ") Please enter your own String : one
if(string == string[:: - 1]): This is Not a Palindrome String
print("This is a Palindrome String")
else:
print("This is Not a Palindrome String")
Reversing a given string Output
string=input("Enter any string:") Enter any string:welcome
revstring=string[::-1] Reverse String= emoclew
print("Reverse String=",revstring)
Program to slice substring using for loop Output
str1="COMPUTER" C
index=0 CO
for i in str1: COM
print (str1[:index+1]) COMP
index+=1 COMPU
COMPUT
COMPUTE
COMPUTER

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 35


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Program to display the number of vowels and Output


consonants in the given string
str1=input ("Enter a string: ") Enter a string: madam
str2="aAeEiIoOuU" The given string contains 2 vowels
v,c=0,0 and 3 consonants
for i in str1:
if i in str2:
v+=1
else:
c+=1
print ("The given string contains %d vowels and %d
consonants"%(v,c))
Python Program to count the occurrences of the Output
substring in a given string
string = input("Enter the string\n") Enter the string
substring = input("Enter the sub string:") He came came came and came
count = string.count(substring) Enter the sub string:came
print("The count is:", count) The count is: 4
String Sorting Output
n=int(input("Enter the number of words to be sorted")) Enter the number of words to be
print("Enter the words:") sorted4
words=list() Enter the words:
for i in range(0,n): Bala
words.append(input()) Rajesh
temp=" " Ramesh
for i in range(len(words)): Kavitha
for j in range(len(words)-i-1): The sorted words are:
if(words[j]>words[j+1]): Bala
temp=words[j] Kavitha
words[j]=words[j+1] Rajesh
words[j+1]=temp Ramesh
print("The sorted words are: ")
for i in range(len(words)):
print(words[i])
Python code to delete all occurrences of a character in Output
a string
str=input("Enter the string:\n") Enter the string:
c=input("Enter the character to remove:\n") engineering
new=str.replace(c,"") Enter the character to remove:
print("String after removing character :",new) e
String after removing character :
nginring

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 36


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Write a program that finds whether a given character Output


is present in a string or not without using built-in
function
def find_ch(s,c): Enter a string:god is great
index=0 Enter the charcater to be searched....r
while index<len(s): r found in string at index : 8
if s[index]==c:
print(c,"found in string at index : ",index)
return
else:
pass
index+=1
print(c,"is not present in the string")
str=input("Enter a string:")
ch=input("Enter the charcater to be searched....")
find_ch(str,ch)
Unit-I

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

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 37


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

that it is ready for instructions.


4. Distinguish between script mode and interactive mode
Interactive mode Script mode
 A way of using the Python interpreter  A way of using the Python interpreter
by typing commands and expressions to read and execute statements in a
at the prompt script
 Can’t save and edit the code  Can save and edit the code
 We can see the results immediately  We cannot see the results immediately
5. Differentiate between compiler and 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

6. List the standard data types in python

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 38


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

7. What is meant by python numbers?


 Number data types store numeric values. Number objects are created when you
assign a value to them.
 Python supports four different numerical types :
o int (signed integers)
o long (long integers, they can also be represented in octal and hexadecimal)
o float (floating point real values)
o complex (complex numbers)
8. What is a Tuple? How literals of type tuple are written? Give example. [AU Jan
2018]
 A tuple may be defined as a finite, static list of numbers or string.
 It contains immutable sequence of values separated by commas.
 The value can be of any type, and they are indexed by integers.
 Literals of type tuple can be enclosed within parenthesis ().
 Example:
>>>t= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
9. What is meant by keyword? Give example. (AU Jan 2019)
 Keywords are the reserved words in Python.
 Keywords are case sensitive.
 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

10. Outline the logic to swap the content of two variables without using third variable.
[May 2019]

a=int(input("Enter the first value :\n"))

b=int(input("Enter the second value :\n"))

a,b=b,a

print("Values after swapping is",a,b)

11. What is a variable?


One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value. The assignment statement gives a
value to a variable.
Eg:

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 39


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

>>> n = 17
>>> pi = 3.14159
12. Write the differences between the symbol / and // in python

/ Division x/y Quotient of x and y


// Floor Division x//y The division of operands where the result is the quotient in
which the digits after the decimal point are removed.

13. What is meant by token? Name token available in python


 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:
 Identifiers/Variables
 Keywords
 Operators
 Delimiters
 Literals
14. What operators does python support?

 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

a=int(input("Enter any number :\n"))

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 40


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

digit_at_ones_place=a%10

print("The digits at one\'s place is %d"%digit_at_ones_place)

Part-B

1. Describe about the concept of precedence and associativity of operators in python.


2. Sketch the structure of interpreter and compiler. Describe the differences between them.
Explain how python works in interactive and script mode with example.
3. Summarize the precedence of mathematical operators in python
4. Appraise the various operators available in python with suitable examples.
5. Describe different data types in python with suitable examples.
6. i) Discuss the difference between tuples and list
ii) Discuss the various operation that can be performed on a tuple and Lists (minimum 5)
with an example program.
7. i) What is membership and identity operators?
ii) Write a program to perform addition, subtraction, multiplication, integer division, floor
division and modulo division on two integer and float.

Unit I PP Prepared by: Mr Balamurugan V, AP/CSE Page 41


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Unit II

PYTHON DATA SETS

Case Sensitive - Scripts - Sequence Types - Tuples - Named Tuples - Sets - Mapping Types -
Dictionaries -Generators – Iterators

Case Sensitive

 Python is a case-sensitive language.


 This means, Variable and variable are not the same.
 Always name identifiers that make sense.
 While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier to figure
out what it does even when you look at your code after a long gap.
 Multiple words can be separated using an underscore, this_is_a_long_variable.

Scripts

 Basically, a script is a text file containing the python statements.


 Python Scripts are reusable code.
 Once the script is created, it can be executed again and again without retyping
 The Scripts are editable.

Creating Scripts in Python

1. Choose File → New File or press Ctrl + N in Python shell window.

2. An untitled blank script text editor will be displayed on screen as shown below

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 1


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

3. Type the following code in Script editor

a =100

b = 350

c = a+b

print ("The Sum=", c)

4. Save the file using File->Save->Filename.py

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 2


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

5. Run the code by pressing F5.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 3


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Sequence Types- Lists

 List is an ordered sequence of items.


 It is a collection of sequence of values belonging of any type.
 It can be written as a list of comma-separated values between square brackets [ ]
 Lists are mutable: (i.e) modifiable: we can change the elements of list at any time we want.
 List Creation
o Syntax: var_name=[element1, element2,….element n]
 Examples:
List1=[ ] Empty list.
List2=[1,2,3] List with values of same type.
List3=[1,"a",2,"s",3,"red",4] List with values of different types.
Reading elements of a List from keyboard

Using append method Output


lst=[] 10
for i in range(5): 20
ele=input() 30
lst.append(ele) 40
print(lst) 50
['10', '20', '30', '40', '50']
Using split () method Output
sequence=input().split() 10 20 30 40 50
print(sequence) ['10', '20', '30', '40', '50']

Basic List Operations

Operations Examples Description


Create a list >>> a=[1,2,3,4,5,6,7,8,9,10] In this way we create a list in
>>> print(a) static manner.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Indexing >>> print(a[0]) Accessing the position in the
1 0th item
>>> print(a[-1]) Accessing last element using
10 negative indexing.
Slicing >>> a[0:3] Prints a part of the list.
[1, 2, 3]
>>> a[0:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 4


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Concatenation >>> b=[90,100] Adding and printing the


>>> print(a+b) items of two lists.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 90, 100]
Repetition >>> print(b*2) Create multiple copies of
[90, 100, 90, 100] same list.
Updating >>> a[0]=700 Updating the list using index
>>> print(a) value.
[700, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Membership >>> 5 in a Returns True if element is
True present in list. Otherwise
>>> 2 not in a returns false.
False
Comparison >>>a=[700, 2, 3, 4, 5, 6, 7, 8, 9, 10] Returns True if all elements in
>>b=[200,300] both elements are same.
>>> a==b Otherwise returns false.
False
>>> a!=b
True
Accessing elements of a List

 The elements of a list are identified by their positions.


 The index [] operator is used to access the elements of a list.
 The following syntax is used to access the elements of a list.
 Syntax: Name_of_Variable [index]
 In python, index value is an integer number which can be positive or negative.
 Positive value of index counts from the beginning of the list.
 Negative value means counting backward from end of the list (i.e. in reverse order).

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])

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 5


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

List Slicing [Start: End]

 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

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

1. Return values but doesn’t change list

List Method Explanation


a) count(x) The count method returns the number of times
Syntax: x appears in the list
list_name.count(x)

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 6


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

List Method Explanation


a) append(value) The append method adds a new element to the
Example: end of a list.
>>> seq.append(6)
>>> print(seq)
[1, 2, 3, 4, 5, 6]
b) extend(list) The extend method takes a list as an argument
Example: and appends all the elements.
>>> seq.extend([7,8,9])
>>> print(seq)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
c) insert(index,value) The insert ( ) function is used to insert an
Example: element at any position of a list.
>>> seq.insert(0,10)
>>> print(seq)
[10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
d) remove(value) Removes the first occurrence of given value
Example: from the list.
>>> seq.remove(10)
>>> print(seq)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 7


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

>>> 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

 Creating a copy of a list is called aliasing.


 When you create a copy both list will be having same memory location.
 Changes in one list will affect another list.
 It is safer to avoid aliasing when you are working with mutable objects.

Example for List Aliasing Output


Nos_List=[1,2,3,4]
temp_List=Nos_List [1, 2, 3, 4]
print(temp_List) [1, 2, 3, 4, 5]
temp_List.append(5)
print(Nos_List)

[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

 The easiest way to clone a list is to use the slice operator.


 Taking any slice of a list creates a new list. In this case, the slice consists of the
whole list.
 The changes made in the cloned list will not be reflected back in the original list.

Example for List Cloning


>>> x=['a','b','c']
>>> y=x[:]
>>> print(x)
['a', 'b', 'c']
>>> print(y)
['a', 'b', 'c']
>>> y[0]='r'
>>> print(y)
['r', 'b', 'c']
>>> print(x)
['a', 'b', 'c']
List deletion

del removes an element from the list.

>>> 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']

>>> del list[1:5]

>>> 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

[<expression> for <element> in sequence if <conditional>]

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 9


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Generating squares of first 10 natural Output


numbers using the concept of List
comprehension
>>> squares = [ x ** 2 for x in range(1,11) ] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> print (squares)
Print the list of even numbers within a given Output
range
odd_even=[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
print(odd_even)
Print positive numbers from the given Output
sequence
num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]
c=[x for x in num if x>=0]
print(c)
[x+3 for x in[1,2,3]] [4,5,6]
>>> str=["this","is","an","example"] ['t', 'i', 'a', 'e']
>>> element=[word[0] for word in str]
>>> print(element)

Nested Lists

 Nested lists are list objects where the elements in the lists can be lists themselves.

Examples using Nested List Output


Nested List Creation
>>> li=[10,20,[30,40,50,60,70,80]] [10, 20, [30, 40, 50, 60, 70, 80]]
Length of nested list
>>> len(li) 3
Length of index 2 6
>>> len(li[2])
>>> li[2][0] # Accessing the first index of the 30
nested list
>>> li[2][-1] # Accessing nested list using 80
negative indexing

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 10


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

>>> 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.

Method Example Description


list() >>> a=(1,2,3,4,5) It converts the given tuple into
>>> a=list(a) list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple() >>> a=[1,2,3,4,5] It convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)

Benefits of tuples

 Tuples are faster than lists.


 If the user wants to protect the data from accidental changes, tuple can be used.

Creating tuples

 Creating tuples is similar to list.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 11


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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=( )

# Tuple with n number elements


Tuple_Name = (E1, E2, E2 ……. En)

# Elements of a tuple without parenthesis


Tuple_Name = E1, E2, E3 ….. En

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')

(i) Creating Tuples using tuple () function

 The tuple ( ) function is used to create Tuples from a list.


 When you create a tuple, from a list, the elements should be enclosed within square
brackets.

Syntax:
Tuple_Name = tuple( [list elements] )

Example :
>> MyTup3=tuple([25,45,90])
>>> print(MyTup3)
(25, 45, 90)
>>> type(MyTup3)
<class 'tuple'>

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 12


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

(ii) Creating Single element 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'>

Accessing values in a 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)

Update and Delete Tuple

 As you know a tuple is immutable, the elements in a tuple cannot be changed.


 Instead of altering values in a tuple, joining two tuples or deleting the entire tuple is
possible.

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.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 13


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

 The + Operator: The concatenation operator is used to join two 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)

 Membership: Returns True if element is present in tuple. Otherwise returns false.


>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
True
>>> 100 in a
False
 Comparison: Returns true if all elements in both tuples are same. Otherwise returns
false.
>>> a=(2,3,4,5,6,7,8,9,10)
>>> b=(2,3,4)
>>> a==b
False
>>> a!=b
True

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 14


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Tuples Methods (or) Built-in functions

Methods Example Description


a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>> a.count(3) Returns the count of the given
1 element

len(tuple) >>> len(a) return the length of the


5 tuple

min(tuple) >>> min(a) return the minimum


1 element in a tuple
max (tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.
>>> print(a)
NameError: name 'a' is not defined
sorted() >> my_tuple=("dog","bird","ant","Cat","elephant") It returns a sorted list but it does
>>> sorted(my_tuple) not sort the tuple itself. The
['ant', 'bird', 'cat', 'dog', 'elephant'] order of the elements inside
>>> my_tuple tuple remains unchanged
('dog', 'bird', 'ant', 'Cat', 'elephant')
sum() >>> my_tuple=(5,10,15,20,25,30) It returns the total of all items on
>>> sum(my_tuple) a tuple
105
tuple() >>> tuple("hello") It converts iterables like string,
('h', 'e', 'l', 'l', 'o') list to a tuple
>>> list=[1,2,3,4,5]
>>> tuple(list)
(1, 2, 3, 4, 5)

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.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 15


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Returning Multiple Values form a Tuple

 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.

Python code to return multiple values from a Tuple Output


def div(a,b): Enter a value:4
r=a%b Enter b value:3
q=a//b Remainder: 1
return(r,q) Quotient: 1
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
r,q=div(a,b)
print("Remainder:",r)
print("Quotient:",q)
Example 2 Output
def min_max(a): Smallest: 1
small=min(a) Biggest: 6
big=max(a)
return(small,big)
a=(1,2,3,4,5,6)
small,big=min_max(a)
print("Smallest:",small)
print("Biggest:",big)

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 16


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Named Tuples

 The Named Tuple is another class, under the collections module.


 Like the dictionary type objects, it contains keys and that are mapped to some values.
 In this case we can access the elements using keys and indexes.

The accessing methods of NamedTuple

 One can access the values stored in Named Tuple using the following
o Indexes
o Keys
o getattr()

Example code to access the values stored in NamedTuple Output


import collections The name and salary of e1: Asim and
#create employee NamedTuple 25000
Employee=collections.namedtuple('Employee',['name','city','salary']) The name and salary of e2: Bala and
#Add two employees 30000
e1=Employee('Asim','Delhi','25000') The City of e1 and e2: Delhi and
e2=Employee('Bala','Chennai','30000') Chennai
#Acess the elements using index
print('The name and salary of e1:',e1[0],'and',e1[2])
#Access the elements using attribute name
print('The name and salary of e2:',e2.name,'and',e2.salary)
#Access the elements using getattr()
print('The city of e1 and e2 is',getattr(e1,'city'),'and',getattr(e2,'city'))

Conversion procedures of NamedTuple

 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.

Example code for conversion procedures of NamedTuple Output


import collections Employee(name='Asim', city='Delhi',
#create employee NamedTuple salary='25000')
Employee=collections.namedtuple('Employee',['name','city','salary']) Employee(name=Bala, city=Chennai,
#List of vales to Employee salary='30000')
my_list=['Asim','Delhi','25000'] OrderedDict([('name', 'Asim'), ('city',
#_make() converts list to named tuple 'Delhi'), ('salary', '25000')])

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 17


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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)

Some additional operations on NamedTuple

 There are some other method like _fields() and _replace().


 Using the _fields() method we can check what are the different fields of NamedTuple.
 The _replace() method is used to replace the value of some other value.

Example code to perform additional operations on NamedTuple Output


import collections Employee(name='Asim', city='Delhi',
#create employee NamedTuple salary='25000')
Employee=collections.namedtuple('Employee',['name','city','salary']) The fields of Employee: ('name', 'city',
#Add two employees 'salary')
e1=Employee('Asim','Delhi','25000') Employee(name='Asim', city='Mumbai',
print(e1) salary='25000')
print(e1._fields)
e1=e1._replace(city="Mumbai")
print(e1)

Sets

 In python, a set is another type of collection data type.


 A Set is a mutable and an unordered collection of elements without duplicates.
 That means the elements within a set cannot be repeated.
 Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc.

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.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 18


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Syntax :

Set_Variable = {E1, E2, E3 …….. En}

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.

Creating sets using list or tuple

 A list or Tuple can be converted as set by using set ( ) function.


 This is very simple procedure.
 First you have to create a list or Tuple then, substitute its variable within set ( ) function as
argument.

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

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 19


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 20


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Method Name Syntax Example Description


add() set.add(elmnt) s={1,2,3}  The add () method adds an element to the set.
t={3,4,5}  If the element already exists, the add () method
s.add(6) does not add the element.
print(s)
Output
{1,2,3,6}
len() len(set) len(s)  To determine how many items a set has, use
4 the len() method.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 21


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

update() set1.update(set2) s.update(t)  The update() method inserts the items in set2
{1,2,3,6,4,5} into set1

remove() set.remove(element) s.remove(6)  If the element (argument) passed to the


{1,2,3,4,5} remove () method doesn't exist, keyError
exception is thrown.

discard() set.discard(element) s.discard(5)  In this method error will not be raised if


{1,2,3,4} element is not present
pop() set.pop() s={1,2,3}  The pop () method removes an arbitrary
s.pop() element from the set and returns the element
print(s) removed.
Output
{2,3}
clear() set.clear() s={1,2,3}  The clear () method doesn’t take any
s.clear() parameters.
print(s)
{}
max() max(set) s={1,3,2,4,5,6}  Returns the maximum element in the set.
a=max(s)
print(a)
6
min() min(set) s={1,3,2,4,5,6}  Returns the minimum element in set.
a=min(s)
print(a)
1
sum() sum(set) s={1,3,2,4,5,6}  Returns the sum of set elements
a=sum(s)
print(a)
21

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

 The syntax to create an empty dictionary can be given as,

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 22


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Syntax :

dictionary_variable= { }
Example
dict={}
print(dict)
Output
{}

 The syntax to create a dictionary with key-value pairs is:

Syntax :

Dictionary_Name = { Key_1: Value_1,


Key_2:Value_2,
……..
Key_n:Value_n
}
Example
dict={'Roll_No':'16/001','Name':'Arnav','Course':'BTech'}
print(dict)
Output
{'Roll_No': '16/001', 'Course': 'BTech', 'Name': 'Arnav'}
 To create a dictionary with one or more key-value pairs one can also use the dict () function.
 The dict () creates a dictionary directly from a sequence of key value pairs.

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}

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 23


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Adding an Item in a Dictionary

 The syntax for adding new item in a dictionary is given as,

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

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 24


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Example
dict={"Name":"Arav","Dept":"IT","RNo":123}
dict['Course']="MTECH"
print(dict)
Output
{'RNo': 123, 'Name': 'Arav', 'Dept': 'IT', 'Course': 'MTECH'}
Deleting items

 del keyword is used to delete one (or) more elements


 To delete or remove all the items in just one statement, use clear () function.
 To remove an entire dictionary from the memory, we can again use the del statement.

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}

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 25


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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'

Looping over a Dictionary

Program to access items in a dictionary using for Output


loop
dict={"Name":"Arav","Dept":"IT","RNo":123} KEYS : Name RNo Dept
print("KEYS : ",end=" ") Values : Arav 123 IT
for key in dict: Dictionary : Name Arav RNo 123 Dept IT
print(key,end=' ')
print("\n Values : ",end=" ")
for val in dict.values():
print(val,end=' ')
print("\n Dictionary : ",end=" ")
for key,val in dict.items():
print(key, val,"\t",end=' ')

Dictionary Methods

Method Example Description


a. copy () >>> a={1:"one",2:"two",3:"three"} Returns a shallow copy (alias) of
>>> b=a.copy() dictionary
>>> print(b)
{1: 'one', 2: 'two', 3: 'three'}
a.items() >>> a.items() Returns a list of (key, value) tuple
dict_items([(1, 'one'), (2, 'two'), (3, 'three')]) pairs

a.keys() >>> a.keys() Returns the list of keys in a dictionary


dict_keys([1, 2, 3])

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 26


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

a.values() >>> a.values() It displays the list of dictionary


dict_values(['one', 'two', 'three']) values

a.pop(Key) >>> a.pop(3) Removes the element with key and


'three' return its value from the dictionary
>>>print(a)
{1: 'one', 2: 'two'}
setdefault(key,value) >>> a.setdefault(3,"three") If key is in the dictionary, return its
'three' value. If key is not present, insert key
>>>print(a) with value of dictionary and return
{1: 'one', 2: 'two', 3: 'three'} dictionary.

a.update() >>> b={4:"four"} It will add dictionary with the


>>> a.update(b) existing dictionary
>>> print(a)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

len(a) 4 It returns the length of the dictionary

clear() >>>a.clear() Removes all elements from the


>>>print(a) dictionary
>>>{}
del(a) >>>del(a) It will delete the entire dictionary

fromkeys() >>> key={"apple","ball"} It creates a dictionary


>>> value="for kids" from key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'ball': 'for kids', 'apple': 'for kids'}
get() dict={"Name":"Arav","Dept":"IT","RNo":1 Display the value of given key
23}
dict.get(“RNo”)
123

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__().

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 27


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 __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.

Example code to demonstrate __iter__() Output


and __next__()
L1=[1,2,3] 1
it=iter(L1) 2
print(it.__next__()) 3
print(it.__next__()) Traceback (most recent call last):
print(it.__next__()) File "main.py", line 14, in <module>
print(it.__next__()) print(it.__next__())
StopIteration
L1=[1,2,3] 1
it=iter(L1) 2
print(next(it)) 3
print(next(it)) Traceback (most recent call last):
print(next(it)) File "main.py", line 14, in <module>
print(next(it)) print(it.__next__())
StopIteration
Creating Own Python Iterator

 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.

Create an iterator that returns numbers, starting Output


with 1, and each sequence will increase by one
(returning 1, 2,3,4,5 etc.):
class MyNumbers: 1
def __iter__(self): 2
self.a = 1 3
return self 4
5
def __next__(self):

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 28


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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:

Example code to stop after 20 iterations Output


class MyNumbers: 1
def __iter__(self): 2
self.a = 1 3
return self 4
5
def __next__(self): 6
if self.a <= 20: 7
x = self.a 8
self.a += 1 9
return x 10
else: 11
raise StopIteration 12
13
myclass = MyNumbers() 14
myiter = iter(myclass) 15
16
for x in myiter: 17
print(x) 18
19
20

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 29


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Creation of Generator function in python

 A generator-function is defined like a normal function, but whenever it needs to generate


a value, it does so with the yield keyword rather than return. If the body of a def contains
yield, the function automatically becomes a generator function.

Example code for creation of Generator function Output


def simpleGeneratorFun(): 1
yield 1 2
yield 2 3
yield 3

# Driver code to check above generator function


for value in simpleGeneratorFun():
print(value)

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

Example code to demonstrate Generator Object Output


def simpleGeneratorFun(): 1
yield 1 2
yield 2 3
yield 3

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 30


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

# x is a generator object
x = simpleGeneratorFun()

# Iterating over the generator object using next


print(next(x)) # In Python 3, __next__()
print(next(x))
print(next(x))

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.

Example code for creation of Generator Expression Output


list = [1,2,3,4,5,6] 1
z = (x**3 for x in list) 8
print(next(z)) 27
print(next(z)) 64
print(next(z))
print(next(z))
Write a program to print the table of the given number Output
using the generator.
def table(n): 15
for i in range(1,11): 30
yield n*i 45
i = i+1 60
75
for i in table(15): 90
print(i) 105
120
135
150

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 31


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Generator Advantages

 Easy to implement
 Memory efficient
 Generate Infinite Sequence

Worked Examples

Write a program that creates a list of numbers from 1 to 20 that Output


are divisible by 4
divBy4=[ ] [0, 4, 8, 12, 16, 20]
for i in range(21):
if (i%4==0):
divBy4.append(i)
print(divBy4)
Write a program to define a list of countries that are a member of Output
BRICS. Check whether a county is member of BRICS or not
country=["India", "Russia", "Srilanka", "China", "Brazil"] Enter the name of the country: India
is_member = input("Enter the name of the country: ") India is the member of BRICS
if is_member in country:
print(is_member, " is the member of BRICS")
else:
print(is_member, " is not a member of BRICS")
Python program to circulate the value of variables Output
def rotate(a,n): [1, 2, 3, 4, 5]
new_list=a[n:]+a[:n] List rotated clockwise by 1= [2, 3, 4, 5,
return new_list 1]
example_list=[1,2,3,4,5] List rotated clockwise by 2= [3, 4, 5, 1,
print(example_list) 2]
my_list=rotate(example_list,1) List rotated anti-clockwise by 2= [4, 5,
print("List rotated clockwise by 1=",my_list) 1, 2, 3]
my_list=rotate(example_list,2)
print("List rotated clockwise by 2=",my_list)
my_list=rotate(example_list,-2)
print("List rotated anti-clockwise by 2=",my_list)
Program to create a list of number in the range 1 to 10. Then delete Output
all the even numbers from the list and print the final list
Num = [] The list of numbers from 1 to 10 = [1,
for x in range(1,11): 2, 3, 4, 5, 6, 7, 8, 9, 10]
Num.append(x) The list after deleting even numbers =
print("The list of numbers from 1 to 10 = ", Num) [1, 3, 5, 7, 9]
for index, i in enumerate(Num):
if(i%2==0):

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 32


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 33


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

elif resp==3: 4.Print multiple times


total=sum(t) Enter your option
print("Sum of the elements : ",total) 2
elif resp==4: Minimum element : 1
m=int(input("Enter the count")) Do you want to continue?(Yes/No)
n=t*m Yes
print(m,'times tuple : ',n) 1.Print first and last element
2.Minimum element
ch=str(input("Do you want to continue?(Yes/No)\n")) 3.Sum of the elements
if ch!="Yes": 4.Print multiple times
break Enter your option
3
Sum of the elements : 15
Do you want to continue?(Yes/No)
Yes
1.Print first and last element
2.Minimum element
3.Sum of the elements
4.Print multiple times
Enter your option
4
Enter the count
3
3 times tuple : (1, 2, 3, 4, 5, 1, 2, 3, 4,
5, 1, 2, 3, 4, 5)
Do you want to continue?(Yes/No)
No
Write a program to find Histogram for the given list of integers. Output
L=input("Enter the input:\n") Enter the input:
L=L.replace("[","") [1,2,3,4,5,1,1,2,3,4,5]
L=L.replace("]","") 1:3
List1=list(map(int,L.split(","))) 2:2
Dict1={} 3:2
Dict2={} 4:2
for i in List1: 5:2
if(i>=0): Enter the input:
if(i not in Dict1): [0,-1,-1,4,4,5]
Dict1[i]=List1.count(i) 0:1
else: 4:2
if(i not in Dict1): 5:1
Dict2[i]=List1.count(i) -1 : 2
for i in Dict1:
print(i,":",Dict1[i])
for i in Dict2:
print(i,":",Dict2[i])

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 34


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

PYTHON DICTIONARY OPERATIONS Output


Write a Python program
To create a dictionary
To add element to the dictionary
To display length of the dictionary
To update element in dictionary
To remove all elements from the dictionary
dict={} 1.Add element to the dictionary
while True: 2.Display the length of the dictionary
print("1.Add element to the dictionary") 3.Update the element
print("2.Display the length of the dictionary") 4.Clear dictionary
print("3.Update the element") 5.Display items
print("4.Clear dictionary") 6.Exit
print("5.Display items") Enter your choice
print("6.Exit") 1
resp=int(input("Enter your choice\n")) Enter the number of elements do you
if(resp==1): want to enter :
j=int(input("Enter the number of elements do you want to enter 2
:\n")) Enter the item :
for i in range(j): pencil
t=input("Enter the item :\n") Enter the price for the item :
u=int(input("Enter the price for the item :\n")) 20
dict[t]=u Enter the item :
if resp==2: pen
print("Length is : \n",len(dict)) Enter the price for the item :
if resp==3: 50
h=input("Enter the item to update :\n") Do you want to continue?(Yes/No)
l=int(input("Enter the new price for the item :\n")) Yes
dict[h]=l 1.Add element to the dictionary
if resp==4: 2.Display the length of the dictionary
dict.clear() 3.Update the element
if resp==5: 4.Clear dictionary
for key in dict: 5.Display items
print(key,"-",dict[key]) 6.Exit
if resp==6: Enter your choice
break 2
ch=input("Do you want to continue?(Yes/No)\n") Length is : 2
if ch=="Yes": Do you want to continue?(Yes/No)
continue Yes
else: 1.Add element to the dictionary
break 2.Display the length of the dictionary
3.Update the element
4.Clear dictionary
5.Display items
6.Exit
Enter you choice

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 35


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 36


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Enter you choice


5
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
6
PYTHON LIST OPERATIONS Output
Write a Python program
To add new elements to the end of the list
To reverse elements in the list
To display same list elements multiple times
To concatenate two lists
To sort the elements in the list in ascending order
a=input("Enter the list\n") Enter the list
a=a.replace("[","") [222,111,000,444,555]
a=a.replace("]","") 1.Insert
a=a.split(',') 2.Reverse
for i in range(len(a)): 3.Display multiple times
a[i]=int(a[i]) 4.Concatenate two lists
while True: 5.Sort the elements in the list in
print("1.Insert") ascending order
print("2.Reverse") Enter your choice:
print("3.Display multiple times") 1
print("4.Concatenate two lists") How many elements do you want to
print("5.Sort the elements in the list in ascending order") insert :
resp=int(input("Enter your choice:\n")) 2
if(resp==1): Enter the element to insert
n=int(input("How many elements do you want to insert :\n")) -31
for i in range(n): Enter the element to insert
element=int(input("Enter the element to insert\n")) -23
a.append(element) Do you want to continue?(Yes/No)
if(resp==2): Yes
print("Reversed List : ",a[::-1]) 1.Insert
if(resp==3): 2.Reverse
cnt=int(input("Enter the count\n")) 3.Display multiple times
print(cnt,'times ',a*2) 4.Concatenate two lists
if(resp==4): 5.Sort the elements in the list in
b=input("Enter new list\n") ascending order
b=b.replace("[","") Enter your choice:
b=b.replace("]","") 2

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 37


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

b=b.split(',') Reversed List : [-23, -31, 555, 444, 0,


for i in range(len(b)): 111, 222]
b[i]=int(b[i]) Do you want to continue?(Yes/No)
print("merged list :",a+b) Yes
if(resp==5): 1.Insert
print("Sorted List : ",sorted(a)) 2.Reverse
ch=input("Do you want to continue?(Yes/No)\n") 3.Display multiple times
if ch=="No": 4.Concatenate two lists
break 5.Sort the elements in the list in
ascending order
Enter your choice:
3
Enter the count
2
2 times [222, 111, 0, 444, 555, -31, -
23, 222, 111, 0, 444, 555, -31, -23]
Do you want to continue?(Yes/No)
Yes
1.Insert
2.Reverse
3.Display multiple times
4.Concatenate two lists
5.Sort the elements in the list in
ascending order
Enter your choice:
4
Enter new list
[1,2,3,4]
merged list : [222, 111, 0, 444, 555, -
31, -23, 1, 2, 3, 4]
Do you want to continue?(Yes/No)
Yes
1.Insert
2.Reverse
3.Display multiple times
4.Concatenate two lists
5.Sort the elements in the list in
ascending order
Enter your choice:
5
Sorted List : [-31, -23, 0, 111, 222,
444, 555]
Do you want to continue?(Yes/No)
No

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 38


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

4. Solve a)[0] * 4 and b) [1, 2, 3] * 3.


>>> [0] * 4 [0, 0, 0, 0]
>>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
5. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
>>> list[3:] [’d’, ’e’, ’f’]
6. Mention any 5 list methods.
append() ,extend () ,sort(), pop(),index(),insert and remove()
7. State the difference between lists and dictionary.
List is a mutable type meaning that it can be modified whereas dictionary is immutable and
is a key value store. Dictionary is not ordered and it requires that the keys are hashable
whereas list can store a sequence of objects in a certain order.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 39


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

8. Mention the 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.
 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
9. What is List mutability in Python? Give an example.
 Python represents all its data as objects. Some of these objects like lists and dictionaries
are mutable, i.e., their content can be changed without changing their identity. Other
objects like integers, floats, strings and tuples are objects that cannot be changed.
 Example:

>>> numbers = [17, 123]

>>> numbers[1] = 5

>>> print numbers [17, 5]

10. What is the benefit of using tuple assignment in Python?


It is often useful to swap the values of two variables. With conventional assignments a
temporary variable would be used. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
11. How will you create a dictionary in python?
 Dictionaries are enclosed by curly braces ({}) and values can be assigned and accessed
using square braces ([]).
 Example:
Dict= {}
Dict[“one”]= “This is one”
Dict[2]= “This is two”
12. How will you get all the keys from the dictionary?
 Using dictionary.keys () function, we can get all the keys from the dictionary object.
 print dict.keys( ) # Prints all the keys
13. How will you get all the values from the dictionary?
 Using dictionary.values () function, we can get all the values from the dictionary
object.
 Example: print dict.values ( ) # prints all the values.
14. Define dictionary.
 Dictionary is an unordered collection of items.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 40


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 In dictionary we access values by looking up a key instead of an index.


 A key can be any string or number.
 Dictionaries in python are implemented using hash table.
 Example
my_dict={1: ‘apple’,2: ‘ball’}
15. Define tuple.
 A tuple is a collection of values of different types.
 Unlike lists, tuple values are indexed by integers.
 The important difference is that tuples are immutable.
 Example: t1=(‘a’, ‘b’, ‘c’)
16. How to traverse a list?
 Traversing a list means accessing and Processing each elements of it
 for loop is mainly used to traverse the list.
 Syntax:
for variable_name in list_name:
Process each items
Print or operations

Example Program Output


colors_list=["red","green","blue","purple"] **********Color List**********
months_list=["Jan","Feb","March","April","May"] colors_list
print("**********Color List**********") colors_list
for i in range(len(colors_list)): colors_list
print("colors_list") colors_list
print("**********Months List********") **********Months List********
for months in months_list: Jan
print(months) Feb
March
April
May
17. How to traverse a dictionary?

Example Program Output


indian_player={1:"dhoni",2:"kholi",3:"shewag",4:"ashwin"} dhoni
for element in indian_player: kholi
print(indian_player[element]) shewag
ashwin
18. Compare and contrast tuples and lists in Python. [A.U Jan 2019]

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.

Unit II PP Prepared by: Mr Balamurugan V, AP/CSE Page 41


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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 II PP Prepared by: Mr Balamurugan V, AP/CSE Page 42


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Unit III

PROGRAMMING PARADIGMS IN PYTHON

Control Structures - Branching - Looping - Exception Handling - Custom Exceptions

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.

There are three important control structures

Sequential Statement

 A sequential statement is composed of a sequence of statements which are executed one


after another.
 When an instruction is executed the execution control moves to the next immediate step.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 1


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Example for Sequential Statement

Example for Sequential Statement Output


# Program to print your name and address - example for Hello! This is Shyam
sequential statement 43, Second Lane, North Car Street, TN
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")

Selection/ Conditional Branching 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

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 2


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Simple if statement

 Simple if is the simplest of all decision making statements.


 Condition should be in the form of relational or logical expression.

Syntax of if statement
if(Condition/ Test Expression): # Header
Statement 1
Statement 2
.
. Suite
.
Statement n
Statement x

 The if structure may include 1 statement or n statements enclosed within if block.


 First, the test expression is evaluated. If test expression is True, the statement of if block
(statement 1 to n) are executed, otherwise these statements will be skipped and the
execution will jump to statement x.

Example Programs for Simple if condition


Program to increment a number if it is Output
positive
x=10 11
if(x>0):
x=x+1
print(x)

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 3


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Program to check the age and print whether Output


eligible for voting
x=int (input("Enter your age :")) Output 1:
if x>=18: Enter your age :34
print ("You are eligible for voting") You are eligible for voting
Output 2:
Enter your age :16
>>>
Program to check both numbers are equal Output
num1=int(input("Enter First Number: ")) Enter First Number: 12
num2=int(input("Enter Second Number: ")) Enter Second Number: 12
if(num1-num2==0): Both numbers entered are equal
print("Both numbers entered are equal")

If - else statement

 The if-else statement takes care of a true as well as a false condition


 The else statement contains the block of code that executes when condition is false
 If the condition is true the statements inside if block gets executed otherwise else part gets
executed

Syntax of if…else statement

if(condition/test expression):
statement block 1
else:
statement block 2
Statement x

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 4


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Example Programs for if..else condition


Odd or even Output
num=int(input("Enter a number:")) Enter a number:3
if num%2==0: Number is odd
print("Number is even")
else:
print("Number is odd")
Leap Year or Not Output
year=int(input("Enter a given year:")) Enter a given year:2000
if(((year%4==0)and(year%100!=0)) or (year%400==0)): The given year 2000 is a Leap
print("The given year",year,"is a Leap Year") Year
else:
print("The given year",year,"is not a Leap Year")
Biggest of Three Numbers Output
a=int(input()) 2
b=int(input()) 3
c=int(input()) 1
if a>b: The biggest of three numbers is
big=a 3
else:
big=b
if c>big:
big=c
print("The biggest of three numbers is",big)
Program to read a character from user and check whether Output
the input character is in upper case or lower case
ch=input("Enter a Character: \n") Enter a Character: A
if(ch>='A' and ch<='Z'):
print(ch,"is UPPERCASE") A is UPPERCASE
else:
print(ch,"is LOWERCASE")
Positive or Negative Output
a=int(input("Enter a number")) Enter a number 8
if(a>=0): Positive Number
print("Positive Number")
else:
print("Negative Number")
Vote Eligibility Output
age = int(input("Enter Age : ")) Enter Age : 19
if age>=18: You are Eligible for Vote.
status="Eligible"
else:
status="Not Eligible"
print("You are",status,"for Vote.")

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 5


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Checking Vowels Output


ch=input("Enter a Character : \n") Enter a Character : A
if(ch=='a' or ch=='A' or ch=='e' or ch=='E' or ch=='i' or ch=='I' A is vowel.
or ch=='o' or ch=='O' or ch=='u' or ch=='U'):
print(ch, "is vowel.")
else:
print(ch,"is consonant.")
Program to illustrate the use of ‘in’ and ‘not in’ in if Output
statement
ch=input ("Enter a character :") Enter a character :x
# to check if the letter is vowel x the letter is not a/b/c
if ch in ('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'):
print (ch,' is a vowel')
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in ('a', 'b', 'c'):
print (ch,'the letter is not a/b/c')

Nested If statement

 When a programmer writes one if statement inside another if statement then it is called a
nested if statement.

Syntax for Nested if statements

if(test expression 1):


if(test expression 2):
Statement block 2
else:
Statement block 3
else:
Statement block 3
Statement block n

Example Program using Nested if statements


Program to find largest of three number Output
using nested if statements
a=int(input()) 5
b=int(input()) 2
c=int(input()) 7
if(a>b): c is large
if(a>c):

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 6


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

print("a is large")
else:
print("c is large")
elif(b>c):
print("b is large")
else:
print("c is large")

If-elif-else

 The elif is short form of else if.


 It is used to check multiple conditions.
 If condition 1 is False, it checks the condition 2 of the next elif block and so on.
 If all the conditions are False, then the else statement is executed.
 The if block can have only one else block.
 But it can have multiple elif blocks.

Example Programs for if-elif-else


Menu Driven Calculator Output
def addition(a,b):
return a+b 1
def subtraction(a,b): 3
return a-b 5

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 7


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

m1=int (input("Enter mark in first subject : "))


m2=int (input("Enter mark in second subject : "))
avg= (m1+m2)/2
if avg>=80:
print("Grade : A")

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 8


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

elif avg>=70 and avg<80:


print("Grade : B")
elif avg>=60 and avg<70:
print("Grade : C")
elif avg>=50 and avg<60:
print("Grade : D")
else:
print("Grade : E")
Roots of Quadratic Equation Output

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:

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 9


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

print("Wrong Input")

Iteration or Looping constructs

 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.

Diagram to illustrate how looping construct gets executed

 Python provides two types of looping constructs


o while loop
o for loop

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

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 10


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Syntax for while statement


statement x
while(condition):
statement block
statement y
 The reserved word while begins with while statement.
 The test condition is a Boolean expression.
 The colon (:) must follow the test condition.
 The statements within while loop will be executed till the condition is true.
 When condition is false the control goes out of the loop.

Flowchart for while loop

Example Program using while loop


Program to illustrate the use of while loop - to Output
print all numbers from 10 to 15
i=10 #intializing part of the control variable 10 11 12 13 14 15
while i<=15:#test condition
print(i,end="\t")#statements - block 1
i=i+1#Updation of the control variable
Sum of n numbers Output
n=int(input("Enter a number"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 11


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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 of odd numbers Output


n=int(input("Enter a number")) Enter a number5
i=1 9
sum=0
while(i<=n):

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 12


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Syntax for loop


for <variable> in <sequence>:
<statement 1>
<statement 2>
…………….
<statement n>
 Here, “variable” stores all value of each item. “Sequence” may be a string, a collection or
a range ( ) which implies the loop’s number.

for loop flowchart

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 13


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

a) Looping through an iterables


 In python, an iterables refers to anything that can be looped over such as string,
list or tuple and it has the _ _iter_ _ method defined.

Example 1: Iterating through list Output with explanation


pets_list=['parrot','rabbit','pigeon','dog'] parrot
for mypets in pets_list: rabbit
print(mypets) pigeon
dog

The first time the program runs through for loop, it


assigns ‘parrot’ to the variable mypets. The
statement print(mypets) then prints the value
‘parrot’. The second time the program loop through
for statement, it assigns the value ‘rabbit’ to mypets
and prints the value ‘rabbit’. The program continues
looping through the list until the end of the list is
reached.
Example 2: Iterating through string Output
message="program" p
for i in message: r
print(i) o
g
r
a
m
Example 3: Iterating through tuple Output
language=("C","C++","Java","Python") C
for x in language: C++
print(x) Java
Python

b) Looping through a sequence of numbers


 Usually in Python, for loop uses the range () function in the sequence to specify the initial,
final and increment values. range () generates a list of values starting from start till stop-1.
 The syntax for range () is as follows:
range (start, stop,[step])
 Where,
o start- refers to the initial value. It is optional i.e., value may be omitted. The default
start value is 0.
o stop- refers to final value.
o step- refers to increment value, this is optional part. Default step value is +1

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 14


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Examples of range () function

Example of Range function Output


for i in range(5): 01234
print(i,end=" ")
for i in range(1,5): 1234
print(i,end=" ")
for i in range(1,10,2): 13579
print(i,end=" ")
for i in range(5,0,-1): 54321
print(i,end=" ")
for i in range(5,0,-2): 531
print(i,end=" ")
for i in range(0,1): 0
print(i,end=" ")
for i in range(1,1): Empty
print(i,end=" ")
for i in range(0): Empty
print(i,end=" ")

Example Program using for loop


Program to check prime number Output
num=int(input("enter any positive integer")) enter any positive integer13
if num>1: 13 is a prime number
for i in range(2,num):
if(num%i==0):
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
Prime number within a given range Output
lower=int(input("Enter the upper Limit")) Enter the upper Limit1
upper=int(input("Enter the Lower Limit")) Enter the Lower Limit50
for n in range(lower,upper+1): 2
if n>1: 3
for i in range(2,n): 5
if(n%i)==0: 7
break 11
else: 13
print(n) 17
19
23
29

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 15


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 16


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

for i in range(n): ****


print("* "*n) ****
****
****
n=int(input("enter n value")) enter n value 4
for i in range(n): 4444
print((str(n)+' ')*n) 4444
4444
4444
n=int(input("enter n value")) enter n value 4
for i in range(n): A
print((chr(65+i)+' ')*(i+1)) BB
CCC
DDDD
n=int(input("enter n value")) enter n value 4
for i in range(n): ****
print('* '*(n-i)) ***
**
*
n=int(input("enter n value")) enter n value 4
for i in range(n): *
print('* '*(i+1)) **
***
****
n=int(input("enter n value")) enter n value 4
for i in range(n): 1
print(' '*(n-i-1)+(str(i+1)+' ')*(i+1)) 22
333
4444

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 Program using nested for loop


Example 1 Output
for i in range(3): Hello
for j in range(2): Hello
print("Hello") Hello
Hello
Hello
Hello

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 17


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

 The keyword break allows a programmer to terminate a loop.


 When the break statement is encountered inside a loop, the loop is immediately terminated
and the program control automatically goes to the first statement following the loop.

Flowchart for break statement

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 18


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Working of break statement

Example for Break Statement Output


for val in "computer": c
if val=="t": o
break m
print(val) p
print("********End of the Program********") u
********End of the Program********
for i in "ECE DEPT": E
if i==" ": C
break E
print(i) ********End of the Program********
print("********End of the Program********")
for i in range(1,100,1):
if i==11:
break
else:
print(i,end=" ")

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 19


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

continue statement

 The continue statement is exactly opposite of the break statement.


 It terminates the current iteration and transfer the control to the next iteration in the loop.

Working of continue statement

Flow chart for continue statement

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 20


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Example for continue Statement Output


s="CSE Department" C
for i in s: S
if i==" ": E
continue D
print(i) e
print("******END OF PROGRAM*****") p
a
r
t
m
e
n
t
******END OF PROGRAM*****
for i in range(1,11,1): 1 2 3 4 6 7 8 9 10
if i==5:
continue
print(i,end=" ")

pass statement

 pass statement in Python programming is a null statement.


 pass statement when executed by the interpreter it is completely ignored.
 Nothing happens when pass is executed, it results in no operation.
 The difference between comment and pass statement in python is that, the interpreter
ignores a comment directly whereas pass is not ignored

Example for pass Statement Output


for letter in "HELLO": Pass: H
pass # this statement is doing nothing Pass: E
print("Pass: ",letter) Pass: L
print("Done") Pass: L
Pass: O
Done

Difference Between break statement and continue 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

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 21


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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

Program for else statement in while loop Output


i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5
Program for else statement in for loop Output
for i in range(3): Enter password: secret
password=input('Enter password:') Correct
if password=='secret':
print("Correct")
break
else:
print("3 incorrect password attempts")

Exception Handling

Introduction to Errors and Exceptions

 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.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 22


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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.

Example for Syntax errors


>>> i=0
>>> if i==0 print(i)
SyntaxError: invalid syntax
Explanation:
‘:’ before keyword print is missing

Logical Errors

 Provides incorrect results.


 Occurs due to wrong algorithm or logic to solve a particular problem.

Exception

 An exception is an error that occurs at runtime.


 An exception is an erroneous condition that arises while program is running.
 The runtime errors occur while program is in execution or program is in running
code.

Example 1 : ZeroDivisionError
a=int(input("Enter first Number"))
b=int(input("Enter second Number"))
print("The result : ",a/b)

Enter first Number 10


Enter second Number 0
Traceback (most recent call last):
File "main.py", line 10, in <module>
print("The result : ",a/b)
ZeroDivisionError: division by zero

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 23


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Syntax for try-except block


try:
statements
except ExceptionName:
statements

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 24


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 Handling Arithmetic Exception

Program to demonstrate the use of try and except blocks Output


to handle ZeroDivisionError divided by zero
try: Enter the first number:10
a=int(input("Enter the first number:")) Enter the second number:2
b=int(input("Enter the second number:")) a = 10
c=a/b b= 2
print('a = ',a) a/b = 5.0
print('b = ',b)
print('a/b = ',c) Enter the first number:10
except ZeroDivisionError: Enter the second number:0
print("You cannot Divide number by Zero") You cannot Divide number by Zero

Multiple Except Blocks

 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.

Example program for multiple except blocks Output


try: Enter the first number:10
a=int(input("Enter the first number:")) Enter the second number:0
b=int(input("Enter the second number:")) You cannot Divide number by Zero
c=a/b
print('a = ',a) Enter the first number:10
print('b = ',b) Enter the second number:p
print('a/b = ',c) Provide int values only
except ZeroDivisionError:
print("You cannot Divide number by Zero")
except ValueError:
print("Provide int values only")

Multiple Exceptions in a Single Block

 An except clause may name multiple exceptions as a parenthesized tuple, as shown in


the program given below.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 25


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Program having except clause handling multiple Output


exceptions simultaneously
try: Invalid Input
print('10'+10)
print(1/0)
except(TypeError,ZeroDivisionError):
print("Invalid Input")

The try-except-finally blocks

 The finally block sometime referred to as finally clause.


 The finally block consists of the finally keyword.
 The finally block is placed after the last except block.
 The specialty of finally block is it will be executed always irrespective of whether
exception is raised or not raised and whether exception is handled or not handled.

Syntax for try-except-finally blocks


try:
#Block of try code
except Exception_Type1:
#It is an exception handler for Exception Type1
........
........
except Exception_TypeN:
#It is an exception handler for Exception TypeN
finally:
#This would always be executed.

Working of finally block if there is no Working of finally block if exception is


exception raised & handled
try: try:
print("try") print("try")
except: print(10/0)
print("except") except:
finally: print("except")
print("finally") finally:
Output print("finally")
try Output
finally try

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 26


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Program using finally keyword Output


L1=[1,2,3,4,5] [1, 2, 3, 4, 5]
try: enter the index to reterive the element10
print(L1) Please check the index
n=int(input("enter the index to reterive the element")) Index Out of bounds
print('index=',n,'Element=',L1[n]) No one can stop me from Running!!!
except IndexError:
print("Please check the index") [1, 2, 3, 4, 5]
print("Index Out of bounds") enter the index to reterive the element2
finally: index = 2 Element = 3
print("No one can stop me from Running!!!")

Except block without exception (or) Default except block

 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.

Example program for default except block Output


try: Enter the first number:10
a=int(input("Enter the first number:")) Enter the second number:p
b=int(input("Enter the second number:")) Default except: Please Provide vaild input
c=a/b
print('a = ',a)
print('b = ',b)
print('a/b = ',c)
except ZeroDivisionError:
print("You cannot Divide number by Zero")
except:
print("Default except: Please Provide vaild input")

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 27


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Try – except – else - finally

 The statement(s) in the else block is executed only if the try clause does not raise exception.

Syntax for try-except-else-finally blocks


try:
#risky code.
except:
#handling code.
#It will be executed if there is any exception in try block.
else:
# It will be executed if there is no exception in try block.
finally:
#It will be executed if and only if whether exception raised or not
raised whether exception handled or not handled.

Example 1 Example 2 Example 3


try: try: try:
print("try") print("try") print("try")
except: print(10/0) print(10/0)
print("Except") except: else:
else: print("Except") print("Else")
print("Else") else: finally:
finally: print("Else") print("finally")
print("finally") finally:
print("finally")
Output Output Output:
try try Error try without except block
Else Except
finally finally

Custom Exceptions (or) User-Defined Exceptions

 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.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 28


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Guess a number using customized exceptions Output


class Error(Exception): Enter a number 3
pass Your guess is too low Try again
class TooSmallError(Error):
pass Enter a number 13
class TooLargeError(Error): Your guess is too high,Try again
pass
num=10 Enter a number10
try: correct
ch=int(input("Enter a number"))
if ch<10:
raise TooSmallError
elif ch>10:
raise TooLargeError
except TooSmallError:
print("Your guess is too low Try again")
except TooLargeError:
print("Your guess is too high,Try again")
else:
print("correct")
Write a program to get the name and age of the people Output
who all are eligible for voting.
class Error(Exception): Enter the Name
pass naveen
class CustomError(Error): Enter the age
pass 25
try: Voter name: naveen
name=input("Enter the Name\n") Voter age: 25
age=int(input("Enter the age\n"))
if(age<18): Enter the Name
raise CustomError shilpa
else: Enter the age
print("Voter name:",name) 12
print("Voter age:",age) CustomException:
except(CustomError): InvalidAgeRangeException
print("CustomException: InvalidAgeRangeException")

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 29


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Part-A

1. Write a Python Program to accept two numbers find the greatest and print the
result (AU Jan 2018)

num1=int(input("Enter first number"))

num2=int(input("enter second number"))

if num1>num2:

largest=num1

else:

largest=num2

print("Largest of entered two numbers is",largest)

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”)

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 30


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

4. Write the differences between break and continue.

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

5. Draw the flow chart for if statement.

6. Define pass statement in python.


 A pass is a null operations in python.
 The interpreter reads and executes the pass statement but returns nothing.
 Syntax: pass

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 31


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

7. Define infinite loop with example.


 The loop becomes infinite loop if a condition never becomes False.
 This results in a loop that never ends. Such a loop is called an infinite loop.

Example:

i=1

while True:

print("Hello:",i)

i=i+1

8. Write a python to count the number of vowels

s=input("enter a string:")

c=0

for i in s:

if i in "aeiouAEIOU":

c=c+1

print("The nummber if vowels in ",s,"is",c)

9. Write a program to accept a word from a user and reverse it.

s=input("enter a string:")

for char in range(len(s)-1,-1,-1):

print(s[char],end="")

10. Write a python code to remove duplicates from a list.

lis=input("Enter a list (space seperated):")

lis1=list(lis.split())

uniq_items=[]

for x in lis1:

if x not in uniq_items:

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 32


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

uniq_items.append(x)

print(uniq_items)

11. Define exceptions in python.


 An exception is an irregular state that is originated by a runtime error in the program.
 An exception is an object that stands for error.
 It bothers the usual flow of the program.
 If the exception object is not fixed and handled appropriately, the interpreter will show an
error message.
12. Write the syntax to handle the exceptions using try..except.
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.

Syntax for try-except block


try:
statements
except ExceptionName:
statements

13. Write a program to perform the division of two numbers by using except clause.

try:

a=int(input("Enter the first number:"))

b=int(input("Enter the second number:"))

c=a/b

print('a = ',a)

print('b = ',b)

print('a/b = ',c)

except ZeroDivisionError:

print("You cannot Divide number by Zero")

14. What is try..finally in python?


The specialty of finally block is it will be executed always irrespective of whether
exception is raised or not raised and whether exception is handled or not handled.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 33


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Syntax for try-except-finally blocks


try:
#Block of try code
except Exception_Type1:
#It is an exception handler for Exception Type1
........
........
except Exception_TypeN:
#It is an exception handler for Exception TypeN
finally:
#This would always be executed.

15. What are exception errors in python?


 IOError
 ImportError
 ValueError
 KeyboardInterrupt
 EOFError.

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.

str1 = input("Please Enter Your Own String : ")

vowels = 0

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 34


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

consonants = 0

for i in str1:

if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i == 'A' or i == 'E' or i == 'I'


or i == 'O' or i == 'U'):

vowels = vowels + 1

else:

consonants = consonants + 1

print("Total Number of Vowels in this String = ", vowels)

print("Total Number of Consonants in this String = ", consonants)

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 35


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Unit IV

MODULES AND RE-USABILITY

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

 Modules refer to a file containing python statements and definitions


 We use modules to break down large programs into small manageable and organized
files
 Modules provide reusability of code

Creating a Module: [User defined]

Example.py

def add(a,b):

result=a+b

return result

How to access user defined module:

Syntax: from python_filename import function_name

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 1


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

from example import add

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

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 2


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

3. Calendar & date-time


 Python’s time and calendar modules keep track of date & times
Example
import calendar
cal=calendar.month(2017,5)
print (cal)
Output
May 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
 Date-time
Example
import datetime
print (datetime.date.today())
Output
2018-10-02
import datetime
print (datetime.datetime.now())
Output
2018-10-02 10:14:53.508789

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 3


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Way to Access the Modules

 Through python import statement


 from…..import statement
 import all names

Through python import statement

Syntax: import function_name

 We can import a module using import statement and access the definitions inside it using
dot operator

Example

import math

print(“the value of pi is”,math.pi)

Output: the value of pi is 3.141592653589793

from…..import statement

Syntax: from python_filename import function_name 1, function_name 2

Example

>>> from math import pi,e

>>> print(pi)

3.141592653589793

>>> print(e)

2.718281828459045

import all names

Syntax: from python file import*

 Important everything with the asterisk (*) symbol is not a good programming practice.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 4


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 This can lead to duplicate definitions for an identifier.


 It also hampers the readability of our code.

>>> from math import*

>>> 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

i. Create a directory and name it with a package name.


ii. Keep sub directories (sub packages) and modules in it.
iii. Create _init_.py in the directory.

Importing Module from a package

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 5


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Syntax

import <packagename>.{<sub package name>}.<Module name>

 {} - specify that there can be any number of sub packages.


 The modules are imported from packages using the dot (.) operator.
 Option 1:

import Game. Level. start


 Option 2:

from Game. Level import start

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.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 6


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Opening a File

 Python has a built-in function open () to open a file.


 While opening a file a user has to specify the name of the file and its mode of operation.
 The mode parameter is a string that specifies how the file will be used (either for read or
write).

General Syntax for 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.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 7


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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:

 With relative file name : input_file=open(“unit5.txt”, “r”)


 With absolute file name: input_file=open(“c:\python\unit5.txt”, “r”)

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

 The write () method is used to write a string to an already opened file.


 Now we are going to overwrite the content of file with new contents by opening a file using
write mode.
 The below program opens the file named test.txt using in the ‘w’ mode for writing data.
 If the file doesn’t exit then open function will create a new file and write data into the
file.
 If the file already exists, the contents of the file will be overwritten with new data.

Program: Writing data into file Output


input_file=open("d:/test.txt",'w') Contents are successfully written to a
input_file.write("OLD CONTENTS ARE REPLACED WITH file
NEW CONTENTS \n")
input_file.write("******ALL THE BEST****** \n")
print("Contents are successfully written to a file")
input_file.close()

After execution

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 8


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 writelines()
o The writelines() method writes the items of a list to the file.
o Syntax: file.writelines (list)

Program: Writing data into file using writelines() Output


input_file=open("d:/test.txt",'w')
lines=["hello\n","welcome\n","python programming"]
input_file.writelines(lines)
input_file.close()

Reading Text from a File

Different methods for reading a file

 Reading a file using read (size) method


 Reading a file using for loop
 Reading a file using readline() method
 Reading a file using readlines() method

Reading a file using read (size) method

 It returns the specified number of characters from the file.


 If size parameter is not specified, it reads and returns up to the end of the file.
 Syntax: fileobject.read([size])

Example

Reading a file using read (size) method


>>> f=open("d:/test.txt",'r')
test.txt
>>> f.read(4)
'Good' Good Morning Everyone
>>> f.read(2)
' M'
>>> f.read()
'orning Everyone'
>>>
Reading a file using for loop

 A file can be read line-by-line using a ‘for loop’.

Reading a file using for loop Output


input_file=open("d:/test.txt",'r') I
for line in input_file: Love
print(line,end=" ") Python
Programming

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 9


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Language
Reading a file using readline () method

 The readline () method is used to read individual lines of a file.


 This method reads a file till the newline, including the newline character.

Reading a file using readline () method


>>> f=open("d:/test.txt",'r')
>>> f.readline()
'I\n'
>>> f.readline()
'Love\n'
>>> f.readline()
'Python\n'
>>> f.readline()
'Programming'
>>> f.readline()
''

Reading a file using readlines () method

 The readlines () method returns a list containing each line in the file as a list item.

Reading a file using readlines () method


>>> f=open("d:/test.txt",'r')
>>> f1=f.readlines()
>>> print(f1)
['I\n', 'Love\n', 'Python\n', 'Programming']
Appending Data

 The append ‘a’ mode of a file is used to append data to the end of an existing file.

Program to append extra lines Output


input_file=open("d:/test.txt",'a')
input_file.write("\nWelcome!!!!")
input_file.close()

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 10


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

with open (“filename”) as file:


Example

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.

The rename () Method

 It takes two arguments the current file name and new file name.
Syntax: os.rename(current_file_name, new_file_name)

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 11


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

The remove method

 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()

Example program for tell () method Output


f=open("d:/test.txt",'r') 0
print(f.tell()) Du
print(f.read(2)) 2
print(f.tell()) rga
print(f.read(3)) 5
print(f.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)

Example program for seek () method Output


f=open("d:/test.txt",'r') 0
print(f.tell()) 3
f.seek(3) 0
print(f.tell())
f.seek(0)
print(f.tell())
Functions

 Functions are “ self-contained” modules of code that accomplish a specific task

Need for function

 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.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 12


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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.

Example program for user-defined function Output


def avg_number(x,y): enter value to a: 5
sum=x+y enter value to b:3
return sum 8
a=int(input("enter value to a: "))
b=int(input("enter value to b:"))
res=avg_number(a,b)
print(res)

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 13


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Finding Square of a given number using Function Output


def square(x): Enter any number to find its
y=x*x square:2
return y Square of : 2 is: 4
num=int(input("Enter any number to find its square:"))
square1=square(num)
print("Square of :",num," is:",square1)

Parameters and Arguments

Parameters

• Parameters are the value(s) provided in the parenthesis when we write function header.

• Example: def my_add(a,b):

Arguments

• Arguments are the value(s) provided in function call/invoke statement

• List of arguments should be supplied in same way as parameters are listed.

• 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.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 14


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Function Arguments

Required Arguments

 The number of arguments in the function call should match exactly with the function
definition

Example program for required arguments Output


def my_details(name,age): Name: george
print("Name:",name) Age: 45
print("Age:",age)
return
my_details("george",45)

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

Example program for keyword arguments Output


def my_details(name,age): Name: george
print("Name:",name) Age: 45

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 15


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Example program for default arguments Output


def my_details(name,age=25): Name:Mani
print("Name:",name) Age:25
print("Age:",age)
return
my_details(name="Mani")

Variable Length Arguments

 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.

Example program for variable length arguments Output


def my_details(*name): rajan rahul micheal arjun
print(*name)
my_details("rajan","rahul","micheal","arjun")
Function Prototype

1. Function without arguments and without return type


2. Function with arguments and without return type
3. Function without arguments and with return type
4. Function with arguments and with return type

i) Function without arguments and without return type

 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

iii) Function without arguments and with return type


 In this type no argument is passed through the function call but output is return to the main
function.

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 16


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

iv) Function with arguments and with return type

 In this type arguments are passed through the function call and output is return to the main
function

Without return type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15
With return type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) return c
c=a+b a=int(input("enter a"))
return c b=int(input("enter b"))
c=add() c=add(a,b)
print(c) print(c)
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15

Anonymous Functions

 In Python, anonymous function is a function that is defined without a name.


 While normal functions are defined using the def keyword, in Python anonymous functions
are defined using the lambda keyword.
 Hence, anonymous functions are also called as lambda functions.

Syntax for Anonymous Functions

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 17


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Example 1 for Anonymous Functions Output


sum = lambda arg1, arg2: arg1 + arg2 The Sum is : 70
print ('The Sum is :', sum(30,40))
Example 2 for Anonymous Functions Output
x = lambda a, b: a * b 30
print(x(5, 6))
Scope-Local and Global

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

 A variable defined outside a function body has a global scope.


 It can be created by defining a variable outside of any function/block.
 A variable with global scope can used anywhere in the program.
 Any modification to global variable is permanent and visible to all functions written in the
file.

Example for Local and Global Variable Output


a=20 Global Variable The value of a in function: 30
def display(): The value of outside function: 20
a=30 Local Variable
print("The value of a in function:",a)
display()
print("The value of outside function:",a)
Using global keyword

Example for Global Variable using global Output


keyword
a=20 The value of a in function: 30
def display(): The value of a outside function: 30
global a
a=30
print("The value of a in function:",a)
display()
print("The value of a outside function:",a)

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 18


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Local and Global Variable with the same name

Example for Local and Global Variable with the Output


same name
def Demo(): I Love Programming
S="I Love Programming" I Love python
print(S)
S="I Love python"
Demo()
print(S)

Difference between local and global scope

Global scope Local scope


 Declared and initialized outside  Declared and initialized inside a
functions function, conditional statement, and/or
loop
 Valid at any point of the script  Valid only within the scope of the
function or statement they belong to
 Example  Example
x=10 def my_function():
def my_function(): X=10
print(x) Print(X)

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

Factorial using Recursion Output


def fact(n): Enter a number:5
if n==0 or n==1: Factorial of 5 is 120
return 1

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 19


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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))

Command Line Programming

 Till now we got input from user using input statement/function.


 There is another method that uses command line arguments.
 Inputs will be passed to the program as an argument from COMMAND PROMPT
 The python sys module provides access to any command-line arguments via the sys.argv.
This serves for two purposes. They are
o sys.argv is the list of command-line arguments
o len(sys.srgv) is the length of arguments including filename
 The elements of argv can be accessed using index.
 Index starts from zero.
 Always sys.argv[0] is our filename
 sys.argv [1],……,sys.argv [n] are arguments.

STEPS:

 Write a program

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 20


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 Save .py extension


 Open command prompt
 Change the path to where the program is being saved
 Execute the program using py filename.py Arg1 Arg2 Arg3 ……….

Example program for command Line arguments


import sys
print(sys.argv)
print(len(sys.agrv))
for ele in sys.argv:
print("Argument:",ele)
Output

Example program to sum all the elements from command line


import sys
sum=0
for i in range(1,len(sys.argv)):
sum+=int(sys.argv[i])
print("result=",sum)

Worked Examples

Sum of list elements using recursion Output


def sum_arr(arr,size): Sample Input 1:
if(size==0): 5
return 0 2
else:
4
return arr[size-1]+sum_arr(arr,size-1)
n=int(input()) 6
a=[] 1

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 21


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

for i in range(0,n): 3
element=int(input()) Sample Output 1:
a.append(element) 16
b=sum_arr(a,n)
print(b)

Find the Power of a Number Using Recursion Output


def power(base,exp): Enter base: 2
if(exp==1):
return(base) Enter exponential value: 5
if(exp!=1):
return(base*power(base,exp-1))
Result: 32
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 22


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

Syntax: from python_filename import function_name

3. What are packages?


 A package is just a way of collecting related modules together within a single tree like
hierarchy
 A well-organized hierarchy of directories for easier access
 Python has packages for directories and modules for files.

4. Write a python script to display the current date and time.


import datetime
print (datetime.datetime.now())
Output
2018-10-02 10:14:53.508789

5. What are the various modes for opening a file?

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

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 23


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

w+ Opens a file for both writing and reading


a+ Opens a file for both appending and reading

6. What is command line argument?


o Inputs will be passed to the program as an argument from COMMAND PROMPT
o The python sys module provides access to any command-line arguments via the
sys.argv. This serves for two purposes. They are
o sys.argv is the list of command-line arguments
o len(sys.srgv) is the length of arguments including filename
o The elements of argv can be accessed using index.
o Index starts from zero.
o Always sys.argv[0] is our filename
o sys.argv [1],……,sys.argv [n] are arguments

7. Write a python code to count the number of word in file


fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)

8. Write a python code to write a data into a text file.


input_file=open("d:/test.txt",'w')
input_file.write("OLD CONTENTS ARE REPLACED WITH NEW CONTENTS \n")
input_file.write("******ALL THE BEST****** \n")
print("Contents are successfully written to a file")
input_file.close()

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):

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 24


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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)

13. Compare local and global variables

Global scope Local scope


 Declared and initialized outside  Declared and initialized inside a
functions function, conditional statement, and/or
loop
 Valid at any point of the script  Valid only within the scope of the
function or statement they belong to
 Example  Example
x=10 def my_function():

Unit III PP Prepared by: Mr Balamurugan V, AP/CSE Page 25


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

def my_function(): X=10


print(x) Print(X)

14. Write the functions for accessing and manipulating files and directories on a disk

os.getcwd() Returns the path of the current working


directory
os.chdir(newdir) Changes the current working directory
os.path.isfile(fname) Returns True if a file exists on the said path or
else returns False.
os.rename(old,new( Renames the old file name to a new file name

15. What are various 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.

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 III PP Prepared by: Mr Balamurugan V, AP/CSE Page 26


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Unit V

OBJECT ORIENTED PROGRAMMING AND DEBUGGING

Object-Oriented Concepts and Terminology - Custom Classes - Attributes and Methods -


Inheritance and Polymorphism Debugging - Debugging Syntax Errors - Debugging Runtime
Errors - Scientific Debugging - Testing - Unit Testing - Profiling

Object Oriented Concepts and Terminology

 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>

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 1


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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 (: ).

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 2


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

o Variables defined inside a class are called as “Class Variable” and


functions are called as “Methods”.
o Class variable and methods are together known as members of the class.
o The class members should be accessed through objects or instance of class.
 Creating Objects
o Once a class is created, next you should create an object or instance of that class.
The process of creating object is called as “Class Instantiation”.

 Accessing class members


o Any class member i.e. class variable or method (function) can be accessed by
using object with a dot (.) operator.

Example : Program to define a class and access Output


its member variables
class Sample: Value of x = 10
#class variables Value of y = 20
x, y = 10, 20 Value of x and y = 30
S=Sample( ) # class instantiation
print("Value of x = ", S.x)
print("Value of y = ", S.y)
print("Value of x and y = ", S.x+S.y)

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.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 3


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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.

Example : Program to print student details using Output


class
class student: rno= 123
rno=123 name=abc
name="abc" branch=CSE
branch="CSE" reading
def read(self):
print("reading")
s=student()
print("rno=",s.rno)
print("name=",s.name)
print("branch=",s.branch)
s.read()
program to check and print if the given number Output
is odd or even using class
class Odd_Even: Output 1
even=0 Enter a value: 4
def check(self,num): 4 is Even number
if num%2==0: Output 2
print(num,"is Even Enter a value: 5
number") 5 is Odd number
else:
print(num,"is odd number")
n=Odd_Even()
x=int(input("Enter a value:"))
n.check(x)
Constructor and Destructor in Python

 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.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 4


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 This constructor function can be defined with or without arguments.

Example : Program to illustrate constructor Output


class Sample: Constructor of class Sample...
def __init__(self, num): The value is : 10
print("Constructor of class Sample...")
self.num=num
print("The value is :", num)
S=Sample(10)

 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.

Example : Program to illustrate destructor Output


class Vehicle: Vehicle created.
def __init__(self): Hello world
print('Vehicle created.') Destructor called, vehicle deleted.

def __del__(self):
print('Destructor called, vehicle deleted.')

car = Vehicle()
print('Hello world')

Sample Program to illustrate classes and objects

Example : Write a program to calculate area and Output


circumference of a circle
class Circle: Enter Radius: 5
pi=3.14 The Area = 78.5
def __init__(self,radius): The Circumference = 31.400000000000002
self.radius=radius
def area(self):

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 5


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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 and Methods in Python

 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”

Python code for accessing attributes of class Output


class emp: Harsh
name='Harsh' True
salary='25000' 152
def show(self):
print self.name
print self.salary
e1 = emp()
# Use getattr instead of e1.name
print getattr(e1,'name')

# returns true if object has attribute


print hasattr(e1,'name')

# sets an attribute
setattr(e1,'height',152)

# returns the value of attribute name height


print getattr(e1,'height')

# delete the attribute

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 6


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

delattr(emp,'salary')

Inheritance in Python

 Inheritance is an important aspect of the object-oriented paradigm.


 Inheritance provides code reusability to the program because we can use an existing class
to create a new class instead of creating it from scratch.
 In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class.
 In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name.

 Syntax:

1. class derived-class(base class):


2. <class-suite>

 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>

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 7


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Example : Single Inheritance Output


class Animal: dog barking
def speak(self): Animal Speaking
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

Multiple Inheritance

 Python provides us the flexibility to inherit multiple base classes in the child class.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 8


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

The syntax to perform multiple inheritance is given below.

1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>

Example : Multiple Inheritance Output


class Calculation1: 30
def Summation(self,a,b): 200
return a+b; 0.5
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(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

Multi-level Inheritance

 Multi-Level inheritance is possible in python like other object-oriented languages.


 Multi-level inheritance is archived when a derived class inherits another derived class.
 There is no limit on the number of levels up to which, the multi-level inheritance is archived
in python.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 9


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

The syntax of multi-level inheritance is given below.

1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>

Example : Multi-level Inheritance Output


class Animal: dog barking
def speak(self): Animal Speaking
print("Animal Speaking") Eating bread...
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 10


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

d.speak()
d.eat()

Hierarchical inheritance

 When more than one derived classes are created from a single base – it is called hierarchical
inheritance.

Example : Hierarchical Inheritance Output


class Parent: PARENT
def pdisplay(self): CHILD1
print("PARENT") PARENT
class child1(Parent): CHILD2
def c1display(self):
print("CHILD1")
class child2(Parent):
def c2display(self):
print("CHILD2")
c1=child1()
c1.pdisplay()
c1.c1display()
c2=child2()
c2.pdisplay()
c2.c2display()

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 11


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

The issubclass(sub,sup) method

 The issubclass(sub, sup) method is used to check the relationships between the specified
classes.
 It returns true if the first class is the subclass of the second class, and false otherwise.

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 (obj, class) method

 The isinstance () method is used to check the relationship between the objects and classes.
It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e.,
class.

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))

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 12


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Polymorphism in Python

 The literal meaning of polymorphism is the condition of occurrence in different forms.


 Polymorphism is a very important concept in programming.
 It refers to the use of a single type entity (method, operator or object) to represent
different types in different scenarios.

Example 1: Polymorphism in Addition Operator

num1 = 1 For integer data types, + operator is used to perform


num2 = 2 arithmetic addition operation.
print(num1+num2)
str1 = "Python" Similarly, for string data types, + operator is used to
str2 = "Programming" perform concatenation.
print(str1+" "+str2)

Function 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.

Example 2: Polymorphic len () 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)

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 13


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

makesound(dogobj)

Method Overriding in Python

 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());

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 14


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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:

1) breakpoint() # in Python 3.7

2) import pdb; pdb.set_trace() # in Python 3.6 and below

Method #1: Using breakpoint () function

 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.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 15


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Commands for debugging:

Method #2: Using pdb module

 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))

In order to run the debugger just type c and press enter.

Testing in Python

 Testing is an investigation conducted to provide stakeholders with information about


the quality of the software product or service under test.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 16


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

 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.

Syntax for Unit Testing in Python


import unittest
class TestCaseDemo(unittest.TestCase):
def setUp(self):
print("setUp method execution...")
def test(self):
print("test method execution..")

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 17


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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:

There are three types of possible test outcomes:

 OK – This means that all the tests are passed.


 FAIL – This means that the test did not pass and an AssertionError exception is raised.
 ERROR – This means that the test raises an exception other than AssertionError.

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()

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 18


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

Profiling in Python

 Python provides many excellent modules to measure the statistics of a program.


 This makes us know where the program is spending too much time and what to do in order to
optimize it.
 It is better to optimize the code in order to increase the efficiency of a program.
 So, perform some standard tests to ensure optimization and we can improve the program in
order to increase the efficiency.

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.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 19


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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

1. Distinguish between classes and objects in python


2. Define Inheritance. Mention its types.
3. What is encapsulation and abstraction?
4. How to debug syntax errors and run-time errors in python? Give examples.
5. Compare Testing and Unit Testing
6. What is polymorphism?
7. Write a python code to create a class named cricket. Create an object to access the
members and methods stored inside the class cricket
8. Write a simple python code to show the working of single inheritance
9. What is multiple and multi-level inheritance?
10. Define hierarchical inheritance.

Part-B

1. Explain the different types of inheritance in python with necessary example programs

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 20


Sri Eshwar College of Engineering (An Autonomous Institution)
Coimbatore- 641 202

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.

Unit V PP Prepared by: Mr Balamurugan V, AP/CSE Page 21

You might also like