Python Workbook
Python Workbook
Lecture No Content
1. Introduction to Python
Why Python?
Features of Python
Installation of Python interpreter
Interpreted Vs Scripting Language
Input and Output in Python
Variables in Python
Operators in Python
2. Flow controls in Python
If statement
If else statement
Ladder if else statement
Loop controls
While loop
For loop
3. Collections in Python
List in Python
Tuple in Python
List Vs. Tuple
Set in Python
Dictionary in Python
4. Function in Python
Why function?
Creation of function
Example applications of function
Recursion
Modules in Python
Import module
From .. import …. Statement
5. Object oriented programming
Pillars of object oriented programming
Class and object
Static and non-static variables
Constructor in Python
Types of constructor in Python
6. Inheritance in Python
Types of inheritance in Python
Single Inheritance
Hierarchical Inheritance
Multiple Inheritance
Multi-level Inheritance
Hybrid Inheritance
7. Polymorphism in Python
Method Overload
Method Overriding
Method Overloading Vs. Method Overriding
Exception handling in Python
Use of try, except and finally
8. Work on String
Built-in methods of string
Work on upper(), lower(), title(), split(), replace() methods
Work on Boolean methods
Lecture – 1 (Introduction to Python)
Are you aware that websites like YouTube and Dropbox make use of Python
Programming in their source code? Python is a commonly used language which one can
easily understand and apply. You can make nearly anything using Python. Most systems
today (Mac, Linux, UNIX, etc.) have Python installed as a default setting since it is an open
source and free language. Upon reading this book, you are going to become fluent in this
awesome code language and see it applied to a variety of examples. No type declaration of
methodology, parameters, functions, or variables (like in other languages) are found in
Python making its code concise and easy. As I said earlier, you can use the language in
everything if you want to build a website, make a game, or even create a search engine. The
big plus of using Python is, an explicit compiler is not necessary since it’s an entirely
interpreted language (Perl, Shell, etc.).
Introduction to Python
Note:- Guido Van Rossum made available python language to the public in 1991.
By using python language we can do the following things:-
1. GUI application development
2. Web application development
3. Data analytics
4. Task automation
5. Test cases implementations
6. Scientific application development
7. Network application development
8. Gaming / animation application development
2. What are different features of Python?
Now we are going to see a step by step guide to download and install the Python language
interpreter.
Python programming language is available for all of the three known platforms for
Windows, Linux/Unix, and Mac OS. Below are the links from where Python interpreters
can be downloaded for these environments.
Steps to install Python on Windows Platform:-
Please follow the below steps:
1. Check for Windows installer if it is 32-bit or 64-bit. Accordingly, download Python
version for Windows platform for the given link.
2. Once downloaded, click on the installer. The below screen will be visible which will
trigger Python installation on Windows.
3. Choose the first option as “Install for all users” and click on the next button to
proceed.
4. Next, the system will ask to select the destination directory. Choose the directory
as shown below and click on Next button.
5. Next, the system will ask to customize Python 3.4.4. Keep the default setup and
click on the Next button as shown in the below screenshot.
6. Installer will start the installation which will take several minutes and the below
screenshot will be visible during this point of time.
7. Once Python interpreter installation is completed, click on the Finish button to
complete the installation on Windows platform.
Operators are used to manipulate the value of operands. Python supports the following
types of operators:-
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Special Operators
Arithmetic Operators:- These operators are used to perform the mathematical operations
like addition, subtraction, multiplication and so on.
Operator Meaning
+ Add two operands (or) unary plus
- Subtract right operand from the left (or) unary minus
* Multiply two operands
/ Divide left operand by right one (result float)
% Modulus – remainder of the division of left operand by right.
// Floor division – division that results into whole number adjusted to
the left in number line.
** Exponent – left operand raised the power of right
x=15
y=4
print(‘x+y=’,x+y)
print(‘x-y=’,x-y)
print(‘x*y=’,x*y)
print(‘x/y=’,x/y)
print(‘x//y=’,x//y)
print(‘x**y=’,x**y)
O/P:-
x+y=19
x-y=11
x*y=60
x/y=3
x//y=3
x**y=50625
x=15.0
y=4
print (‘x/y = ’,x/y)
print(‘x//y=’,x//y)
O/P:-
x/y=3.75
x//y=3.0
Example Application 3:-
x=’softpro’
y=2
print(‘x*y=’,x*y)
print(‘y*x=’,y*x)
O/P:
x*y=SoftproSoftpro
y*x=SoftproSoftpro
Operator Meaning
> Greater than – true if left operand is greater than right one.
< Less than – true if left operand is less than right one.
== Equal to – True if both operands are equal.
!= Not equal to – True if both not equal
>= Greater than (or) equal to – true if left operand is greater than or
equal to right
<= Less than (or) equal to – True if left operand is less than or equal to
right.
x=10
y=12
print(‘x>y is’,x>y)
print(‘x<y is’,x<y)
print(‘x==y is’,x==y)
print(‘x!=y is’,x!=y)
print(‘x>=y is’,x>=y)
print(‘x<=y is’,x<=y)
O/P:-
x>y is False
x<y is True
x==y is False
x!=y is True
x>=y is False
x<=y is True
Example Application 5:-
x=’softpro’
y=’softpro’
print(‘x>y is’,x>y)
print(‘x<y is’,x<y)
print(‘x==y is’,x==y)
print(‘x!=y is’,x!=y)
print(‘x>=y is’,x>=y)
print(‘x<=y is’,x<=y)
O/P:-
x>y is False
x<y is False
x==y is True
x!=y is False
x>=y is True
x<=y is True
Logical Operator:-
They are used to perform the logical operator like and, or, not.
Logical operators return either True or False values.
Operator Meaning
And True if both operands are True
Or True if either of the operand is True
Not True if operand is False (complements the operand)
x=True
y=False
print (‘x and y is’,x and y)
print (‘x or y is’,x or y)
print (‘not x is’,not x)
O/P:-
x and y is False
x or y is True
not x is False
Bitwise operator:-
These operators are used to perform the operations on the values based on the bits.
Operator Meaning
& Bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift
<< Bitwise left shift
x=10
y=4
print(‘x&y is : ’,x&y)
print(‘x|y is : ’,x|y)
print(‘~x is : ’,~x)
print(‘x^y is : ’,x^y)
print(‘x>>2 is : ’,x>>2)
print(‘x<<2y is : ’,x<<2)
O/P:-
x&y is 0
x|y is 14
~x is -11
x^y is14
x>>2 is 2
x<<y is 40
Note:- Bitwise operators internally converts the operands values in the form of binary
format and performs the operation and gives the results in the form of decimal format.
Assignment Operators:-
x=10
print(‘x=10’,x)
x+=5
print(‘x+=5 : ’,x)
x-=5
print(‘x-=5 : ’,x)
x*=5
print(‘x*=5 : ’,x)
x**=5
print(‘x**=5 : ’,x)
x/=5
print(‘x/=5 : ’,x)
x%=5
print(‘x%=5 : ’,x)
x//=5
print(‘x//=5 : ’,x)
y=20
y&=10
print(‘y&=10 : ’,y)
y/=30
print(‘y/=30 : ’,y)
y^=10
print(‘y^=10 : ’,y)
y>>=3
print(‘y>>=3 : ’,y)
y<<=3
print(‘y<<=3 : ’,y)
O/P:-
x=10 : 10
x+=5 : 15
x-=5 : 10
x*=5 : 50
x**=5 : 312500000
x/=5 : 62500000
x%=5 : 40
x//=10 : 0
y&=10 : 0
y|=30 : 30
y^=10 : 20
y>>=3 : 2
y<<=3 : 16
Special Operators:-
Python supports the two types of special operators:-
1. Identity Operators
2. Membership Operators
Identity operators:-
Identity operators are used to compare the addresses of the memory locations
which are pointed by the operands.
Identity operators’ return true (or) false.
Operator Meaning
Is True if the operands are identical (refer to the same object)
is not True if the operands are not identical (do not refer to the same object)
x1=5
y1=5
x2=’hello’
y2=’hello’
print(‘x1 is y1 : ’,x1 is y1)
print(‘x1 is not y1 : ’,x1 is not y1)
print(‘x2 is y2 : ’,x2 is y2)
print(‘x2 is not y2 : ’,x2 is not y2)
O/P:-
x1 is y1 : True
x1 is not y1 : False
x2 is y2 : True
x2 is not y2 False
Membership Operators:-
Membership operators are used to search for a particular element is a string, list, tuple, set
and so on. Relationship operators return True or False values.
Operator Meaning
In True if value/ variable is found in sequence
not in True if value/ variable is not found in sequence
x=’hello world’
print(‘h’ in x)
print(‘h’ not in x)
print(‘hello’ in x)
print(‘hello’ not in x)
O/P:-
True
False
True
False
Operator’s precedence:-
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
*/%// Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right shift and left bitwise shift
<= < > >= Comparison operators
== != Equality operator
= %= /= -= Assignment operator
is is not Identity operators
in not in Membership operators
not or and Logical operators
Example Application 11:-
a=20
b=10
c=15
d=5
e=0
e=(a+b)*c/d
print (‘value of (a+b)*c/d is’,e)
e=((a+b)*c)/d
print (‘value of ((a+b)*c)/d is’,e)
e=(a+b)*(c/d)
print (‘value of (a+b)*(c/d) is’,e)
e=a+(b*c)/d
print (‘value of a+(b*c)/d is’,e)
O/P:-
value of (a+b)*c/d is 90
value of ((a+b)*c)/d is 90
value of (a+b)*(c/d) is 90
value of a+(b*c)/d is 50
Reserve words in any programming language are special commands that compiler or
interpreters understands, and these reserve words cannot be used as a constant or variable,
or any other identifier names in that programming language.
Python has the following reserve words, and all such keywords contain lowercase letters
only.
4. How many types of variables in Python?
Variables in any programming language are the names of the reference to the reserved
memory locations which are used to store values. Similarly, when we are creating a
variable in Python then we are reserving some space in the memory.
These variables have their own data type. Based on the type, the interpreter allocates
memory and decides what kind of data can be stored in these reserved memory
locations.
Characters, integers, decimals, etc. are the different data types which can be assigned to
such variables.
In the Python language, equal sign (=) is used to assign values to the variables. Such
variables do not need explicit declaration. When we assign a value to a variable, the
declaration or creation happens automatically.
The operand to the left of the equal sign (=) is the name of the variable and the operand
to the right of the equal sign (=) is the value stored in the variable. This is demonstrated
in the below example.
In the above example, the variable name ‘number’ has an integer value therefore, it
behaves as an integer without any data type declaration. Similarly, the variable name
‘decimal’ has a floating value and variable name ‘name’ has a string value. Python is a
very flexible language since it automatically determines the data type once the value is
assigned to the variable.
Technical Tasks:-
1. Write a Python program to print a message on screen.
print(“Hello Python”)
O/P:-
Hello Python
O/P:-
Enter first number : 10
Enter second number : 2
Summation=12
Subtraction=8
Multiplication=20
Division=5.0
O/P:-
Enter length of cuboid : 10
Enter breadth of cuboid : 5
Enter height of cuboid : 4
Volume of cuboid=200
Surface Area of cuboid=220
5. Write a program in python to calculate gross salary. In this program take basic
salary as input then calculate HRA and DA. HRA should be 10% of basic salary and
DA should be 50% of basic salary. Then find gross salary as sum of basic salary, HRA
and DA.
O/P:-
Enter basic salary : 5000
Basic salary=5000
House Rent Allowances=500
Dearness Allowances=2500
Gross Salary=8000
O/P:-
Enter value of p : 10000
Enter value of r : 5
Enter value of t : 5
Simple Interest=2500.0
Interview Questions:-
1. What is python?
Python is an interpreted, object oriented, high level programming language with
dynamic semantics.
2. What are different features of Python?
Features of Python are given below:-
i. Python is an interpreted language.
ii. Python is object oriented language
iii. Python is a multipurpose programming language.
iv. Python supports dynamic semantics.
v. Python is an open source programming language.
vi. Python supports automatic garbage collection.
vii. Write less line of code then other language.
4. What is variable?
Variables are value containers, they create space in memory.
5. What is keyword?
Keywords are reserved word. The meaning of keywords is pre-defined into compiler.
6. What is operator?
Operators are the symbols which are used to perform operations on operands.
7. What is object oriented programming system?
Object oriented programming system is a mechanism of software development.
8. What is open source?
The source code of open source technology is open for all software vendors. A
software engineer can make changes in source code of open source technology.
Multiple choice Questions Set - 1:-
Answer Key:-
1. D 2. D 3. A 4. c
Answer key:-
1. D 2. D 3. C 4. D
Conditional Statements:-
Conditional statements are used to decide whether code has to be execute (or) skip
based on the evaluation of the condition.
After evaluating the condition, it should return either True or False value.
Condition:- Any expression which returns either True (or) False value after evaluating that
expression is known as condition.
Block:- All the statements which are following same space indentation is known as “Block”.
if condition :
stmt1
stmt2
else:
stmt3
stmt4
In if-else condition returns True then it will execute if block otherwise it will execute
else block.
elif:-
syntax:-
if condition:
stmt1
stmt2
elif condition:
stmt3
stmt4
else:
stmt5
stmt6
for loop:- for loop executes the set of statements (or) blocks with respect to every, element
of the string/ collection objects.
syntax:-
for variablename in string / collection variable:
…………………
………………..
range():- range() generate the group of values based on the given range and gives it as a list.
If you have many conditions and you want to execute block of code based on those
conditions then you can use ladder if – else.
if condition1:
#code1
elif condition2:
#code2
else:
#code3
3. Describe while loop in Python?
While is a loop control in Python. It is an entry loop control. The syntax of while loop
is given below:-
Technical Tasks:-
name=input(‘enter name : ’)
if name == ‘brijesh’
print(‘Hi’,name)
print (‘Hello World’)
O/P1:-
enter name : brijesh
Hi, brijesh
O/P2:-
enter name : ravi
Hello World
name=input(‘enter name : ’)
if name==’brijesh’:
print(‘Hi’,name)
else:
print(‘Hi, Stranger’)
print(‘Hello World’)
O/P1:-
enter name : brijesh
Hi brijesh
Hello World
O/P2:-
enter name : ‘rohit’
Hi, Stranger
Hello World
name=input(‘enter name : ’)
age=int(input(‘enter age : ’))
if age<15:
print (name,’you are kid’)
elif age<40:
print (name,’you are young’)
elif age<100:
print (name,’you are old’)
else:
print (name,’you are alian’)
print (‘Hello, World’)
O/P1:-
enter name : tom
enter age : 12
tom, you are kid
Hello, World
O/P2:-
enter name : priya
enter age : 20
priya, you are young
Hello, World
O/P1:-
Enter first no : 100
Enter second no : 50
100 is big
O/P2:-
Enter first no : 100
Enter second no : 200
200 is big
O/P:-
Enter first number : 100
Enter second number : 500
Enter third number : 200
500 is big.
Output 1:-
Enter a number : 4
Number is even
Output 2:-
Enter a number : 5
Number is odd
O/P:-
Output:-
Enter basic salary : 5000
Basic Salary=5000.0
HRA=1000.0
DA=3000.0
Gross Salary=9000.0
Output:-
Enter number of units consumed : 200
Your bill=510.0
O/P:-
Enter a number to find factorial : 5
Factorial=120
O/P:-
Enter a number to find sum of digits : 123
Sum of digits=6
11. Write a Python program to reverse the digits of given number.
O/P:-
Enter a number : 123
Reverse No=321
O/P:-
Enter a number : 5
5 is prime
O/P:-
Enter a number : 5
5*1=5
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
O/P:-
How many terms you want in series? 5
0
1
1
2
3
Interview Questions:-
If we want to represent a group of individual objects as a single entity where insertion order
preserved and duplicates are allowed, then we should go for List.
Python supports both positive and negative indexes. +ve index means from left to right
whereas negative index means right to left
[10,"A","B", 20, 30, 10]
We can use List, Tuple and Set to represent a group of individual objects as a single
entity.
If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
Eg:
rollno----name
phone number--address
ipaddress---domain name
Duplicate keys are not allowed but values can be duplicated.
Heterogeneous objects are allowed for both key and values.
Insertion order is not preserved.
Dictionaries are mutable.
Dictionaries are dynamic.
Indexing and slicing concepts are not applicable.
Note: In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it is
known as "Hash".
d[100]="John"
d[200]="Black"
d[300]="White"
print(d) #{100: 'John', 200: 'Black', 300: 'White'}
If we know data in advance then we can create dictionary as follows
d={100:'John' ,200:'Black', 300:'White'}
d={key:value, key:value}
List Tuple
1) List is a Group of Comma separated 1) Tuple is a Group of Comma separated
Values within Square Brackets and Square Values within Parenthesis and Parenthesis
Brackets are mandatory. are optional.
Eg: i = [10, 20, 30, 40] Eg: t = (10, 20, 30, 40)
t = 10, 20, 30, 40
2) List Objects are Mutable i.e. once we 2) Tuple Objects are Immutable i.e. once
creates List Object we can perform any we creates Tuple Object we cannot change
changes in that Object. its content.
Eg: i[1] = 70 t[1] = 70 ==> ValueError: tuple object does
not support item assignment.
3) If the Content is not fixed and keep on 3) If the content is fixed and never changes
changing then we should go for List. then we should go for Tuple.
4) List Objects can not used as Keys for 4) Tuple Objects can be used as Keys for
Dictionaries because Keys should be Dictionaries because Keys should be
Hashable and Immutable. Hashable and Immutable.
Output:-
[]
<class 'list'>
list=eval(input("Enter List:"))
print(list)
print(type(list))
Output:-
Enter List:[10,20,30,40]
[10, 20, 30, 40]
<class 'list'>
4. How to create list with split function?
s="Learning Python is very very easy !!!"
l=s.split()
print(l)
print(type(l))
Output:-
['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
<class 'list'>
We can access elements of the list either by using index or by using slice operator(:)
1. By using index:
List follows zero based index. ie index of first element is zero.
List supports both +ve and -ve indexes.
+ve index meant for Left to Right
-ve index meant for Right to Left
list=[10,20,30,40]
print(list[0]) ==>10
print(list[-1]) ==>40
print(list[10]) ==>IndexError: list index out of range
2. By using slice operator:
Syntax:
list2= list1[start:stop:step]
start ==>it indicates the index where slice has to start default value is 0
stop ===>It indicates the index where slice has to end default value is max allowed index of
list i.e. length of the list
step ==>increment value default value is 1
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)
Output:-
['A', 'B', 'C']
To add all elements to list upto 100 which are divisible by 10.
list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)
Output:-
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
order1=["Dosa","Pizza","Burger"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)
Output:-
['Dosa', 'Pizza', 'Burger', 'RC', 'KF', 'FO']
4. remove() function:- We can use this function to remove specified item from the list. If the
item present multiple times then only first occurrence will be removed.
n=[10,20,10,30]
n.remove(10)
print(n)
Output:-
[20, 10, 30]
If the specified item not present in list then we will get ValueError
n=[10,20,10,30]
n.remove(40)
print(n)
ValueError: list.remove(x): x not in list
Note: Hence before using remove() method first we have to check specified element
present in the list or not by using in operator.
5. pop() function:- It removes and returns the last element of the list. This is only function
which manipulates list and returns some element.
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)
Output:-
40
30
[10, 20]
If the list is empty then pop() function raises IndexError
Eg:
n=[]
print(n.pop()) ==> IndexError: pop from empty list
Note:
1. pop() is the only function which manipulates the list and returns some value.
2. In general we can use append() and pop() functions to implement stack data structure
by using list, which follows LIFO(Last In First Out) order.
In general we can use pop() function to remove last element of the list. But we can use to
remove elements based on index.
n.pop(index)===>To remove and return element present at specified index.
n.pop()==>To remove and return last element of the list.
n=[10,20,30,40,50,60]
print(n.pop()) #60
print(n.pop(1)) #20
print(n.pop(10)) ==>IndexError: pop index out of range
Note:
List objects are dynamic. i.e based on our requirement we can increase and decrease the
size.
append(),insert() ,extend() ===>for increasing the size/growable nature
remove(), pop() ======>for decreasing the size /shrinking nature
n=[20,10,"A","B"]
n.sort()
print(n)
TypeError: '<' not supported between instances of 'str' and 'int'
s={10,20,30,40}
print(s)
print(type(s))
Output:-
{40, 10, 20, 30}
<class 'set'>
s=set(range(5))
print(s) #{0, 1, 2, 3, 4}
Note: While creating empty set we have to take special care. Compulsory we should use
set() function.
s={} ==>It is treated as dictionary but not empty set.
s={10,20,30}
s.add(40)
print(s) #{40, 10, 20, 30}
2. update(x,y,z):
To add multiple items to the set.
Arguments are not individual elements and these are iterable objects like List, range
etc.
All elements present in the given iterable objects will be added to the set.
s={10,20,30}
l=[40,50,60,10]
s.update(l, range(5))
print(s)
Output:
{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
s={10,20,30}
s1=s.copy()
print(s1)
4. pop():- It removes and returns some random element from the set.
s={40,10,30,20}
print(s)
print(s.pop())
print(s)
Output
{40, 10, 20, 30}
40
{10, 20, 30}
5. remove(x):- It removes specified element from the set. If the specified element not
present in the Set then we will get KeyError.
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) ==>KeyError: 50
6. discard(x):- It removes the specified element from the set. If the specified element not
present in the set then we won't get any error.
s={10,20,30}
s.discard(10)
print(s) ===>{20, 30}
s.discard(50)
print(s) ==>{20, 30}
13. What is the difference between add() and update() functions in set?
We can use add() to add individual item to the Set, where as we can use update() function
to add multiple items to Set.
add() function can take only one argument where as update() function can take any
number of arguments but all arguments should be iterable objects.
d={} or d=dict()
We are creating empty dictionary. We can add entries as follows:-
d[100]="John"
d[200]="Black"
d[300]="White"
print(d) #{100: 'John', 200: 'Black', 300: 'White'}
If we know data in advance then we can create dictionary as follows
d={100:'John' ,200:'Black', 300:'White'}
d={key:value, key:value}
Technical Tasks:-
1. WAP to create a list by taking input from user and display list elements.
list1=[]
n=int(input(“How many elements you want in list? ”))
print(“Enter”,n,”elements”)
for i in range(n):
e=eval(input())
list1.insert(i,e)
print(“You have entered following elements”)
for e in list1:
print(e)
O/P:-
How many elements you want in list? 5
Enter 5 elements
10
20
30
“A”
“B”
You have entered following elements
10
20
30
A
B
2. WAP to create a list of five numbers and find maximum and minimum number.
list1=[10,20,30,40,50]
print(“Maximum Number=”,max(list1))
print(“Minimum Number=”,min(list1))
O/P:-
Maximum Number=50
Minimum Number=10
3. WAP to create a list with five names now display names in ascending and
descending order.
list1=[]
print(“Enter five names to the list”)
for c in range(5):
name=input()
list1.insert(c,name)
list1.sort()
print(“Names in ascending order”)
for n in list1:
print(n)
list1.reverse()
print(“Names in descending order”)
for n in list1:
print(n)
tup1=(10,20,30,40,50)
print(tup1)
print(“Length=”,len(tup1))
print(“Sum=”,sum(tup1))
print(“Maximum value=”,max(tup1))
print(“Minimum value=”,min(tup1))
5. Write a program to enter name and percentage marks in a dictionary and display
information on the screen.
rec={}
n=int(input("Enter number of students: "))
i=1
while i <=n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of marks")
for x in rec:
print("\t",x,"\t\t",rec[x])
Output:
Enter number of students: 3
Enter Student Name: durga
Enter % of Marks of Student: 60%
Enter Student Name: ravi
Enter % of Marks of Student: 70%
Enter Student Name: shiva
Enter % of Marks of Student: 80%
Name of Student % of marks
durga 60%
ravi 70 %
shiva 80%
6. Write a program to find number of occurrences of each vowel present in the given
string?
Output:
Enter any word: doganimaldoganimal
a occurred 4 times
i occurred 2 times
o occurred 2 times
Interview Questions:-
1. What is list in python?
List is a collection in python which is used to store multiple values of different data
types.
2. What is tuple in python?
Tuple is also a collection in python which is used to store multiple values of different
data types. Tuple is immutable whereas list is mutable.
3. What is dictionary in python?
Dictionary is a collection in python which stores elements in key and value pair.
4. What is difference between list and tuple?
List Tuple
1) List is a Group of Comma separated 1) Tuple is a Group of Comma separated
Values within Square Brackets and Square Values within Parenthesis and Parenthesis
Brackets are mandatory. are optional.
Eg: i = [10, 20, 30, 40] Eg: t = (10, 20, 30, 40)
t = 10, 20, 30, 40
2) List Objects are Mutable i.e. once we 2) Tuple Objects are Immutable i.e. once
creates List Object we can perform any we creates Tuple Object we cannot change
changes in that Object. its content.
Eg: i[1] = 70 t[1] = 70 ==> ValueError: tuple object does
not support item assignment.
3) If the Content is not fixed and keep on 3) If the content is fixed and never changes
changing then we should go for List. then we should go for Tuple.
4) List Objects can not used as Keys for 4) Tuple Objects can be used as Keys for
Dictionaries because Keys should be Dictionaries because Keys should be
Hashable and Immutable. Hashable and Immutable.
append() insert()
In List when we add any element it will In List we can insert any element in
come in last i.e. it will be last element. particular index number
Answer Key:-
1. d 2. a 3. c 4. d 5. c 6. b 7. b
Answer key:-
1. B 2. b 3. b 4. d 5. b
2. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}
a) { }
b) set()
c) [ ]
d) ( )
a) print(len(a))
b) print(min(a))
c) a.remove(5)
d) a[2]=45
a) a={5,5,6,7}
b) a={5,6,7}
c) Error as there is no add function for set data type
d) Error as 5 already exists in the set
s=set()
type(s)
a) <’set’>
b) <class ‘set’>
c) set
d) class set
a) pop
b) remove
c) update
d) sum
Answer key:-
1. d 2. a 3. b 4. d 5. b 6. b 7. d
2. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do
we use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)
Answer Key:-
1. d 2. c 3. b 4. c 5. b 6. c 7. c 8. c
Lecture – 4 (Function and Module in Python)
1. Built in Functions
2. User Defined Functions
1. Built in Functions:
The functions which are coming along with Python software automatically, are called built
in functions or pre defined functions
Eg:
id()
type()
input()
eval()
etc..
A group of functions, variables and classes saved to a file, which is nothing but module.
Every Python file (.py) acts as a module.
x=888
def add(a,b):
print("The Sum:",a+b)
def product(a,b):
print("The Product:",a*b)
test.py:
import mymath
print(mymath.x)
mymath.add(10,20)
mymath.product(10,20)
Output:
888
The Sum: 30
The Product: 200
Note:
Whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently.
Example Application :
import mymath as m
Here mymath is original module name and m is alias name.
We can access members by using alias name m.
test.py:
import mymath as m
print(m.x)
m.add(10,20)
m.product(10,20)
Example Application :
import modulename
import module1,module2,module3
import module1 as m
import module1 as m1,module2 as m2,module3
from module import member
from module import member1,member2,member3
from module import member1 as x
from module import *
Member aliasing:
Parameters are inputs to the function. If a function contains parameters, then at the time of
calling, compulsory we should provide values otherwise we will get error.
Example Application: Write a function to take name of the student as input and print wish
message by name.
def wish(name):
print("Hello",name," Good Morning")
wish("John")
wish("Kim")
Output:
Hello John Good Morning
Hello Kim Good Morning
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
Example Application: Write a function to accept 2 numbers as input and return sum.
def add(x,y):
return x+y
result=add(10,20)
print("The sum is",result)
print("The sum is",add(100,200))
The sum is 30
The sum is 300
3. How to return multiple values by a function?
In other languages like C, C++ and Java, function can return at most one value. But in
Python, a function can return any number of values.
Example Application:
def sum_sub(a,b):
sum=a+b
sub=a-b
return sum,sub
x,y=sum_sub(100,50)
print("The Sum is :",x)
print("The Subtraction is :",y)
Output:
The Sum is : 150
The Subtraction is : 50
Technical Tasks:-
1. WAP to find area and perimeter of rectangle using user defined function.
def area(x,y):
return (x+y)
def perimeter(x,y):
return 2*(x+y)
l=int(input(“Enter length of rectangle : ”))
b=int(input(“Enter breadth of rectangle : ”))
print(“Area of rectangle=”,area(l,b))
print(“Perimeter of rectangle=”,perimeter(l,b))
O/P:-
Enter length of rectangle : 10
Enter breadth of rectangle : 5
Area of rectangle=50
Perimeter of rectangle=30
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
x=int(input(“Enter a number to find factorial : ”))
print(“Factorial=”,fact(x))
O/P:- Enter a number to find factorial : 5
Factorial=120
def calc(x,y):
return [x+y,x-y,x*y,x/y]
a=int(input(“Enter first no : ”))
b=int(input(“Enter second no : ”))
res=calc(a,b)
print(“Summation=”,res[0])
print(“Subtraction=”,res[1])
print(“Multiplication=”,res[2])
print(“Division=”,res[3])
O/P:-
Enter first no : 10
Enter second no : 2
Summation=12
Subtraction=8
Multiplication=20
Division=5.0
4. WAP to create a module named myutil in this module create two functions add()
and greatest(). In add() function write code to return sum of two numbers and in
greatest() function write code to return greatest number in two numbers. Now test
module myutil.
myutil.py
def add(x,y):
return x+y
def greatest(x,y):
if x>y:
return x
else:
return y
test.py
import myutil
a=int(input(“Enter first no : ”))
b=int(input(“Enter second no : ”))
print(“Sum=”,myutil.add(a,b))
print(“Greatest=”,myutil.greatest(a,b))
O/P:-
Enter first no : 10
Enter second no : 20
Sum=30
Greatest=20
Interview Questions:-
1. What is function?
Function is a named block of code which perform specific task.
2. What are advantages of functions?
By using function you can avoid to write same code over and over.
3. What is Recursion?
When a function call itself, then it is called ‘Recursion’.
4. How to create function in python?
In python you can create function by using def keyword followed by function name.
The syntax of function creation is given below:-
def function_name(parameters):
#code
5. What is module in python?
Module is a collection of functions , classes and submodules.
Answer Key:-
1. a 2. c 3. d 4. b 5. d 6. d 7. b
3. Program code making use of a given module is called a ______ of the module.
a) Client
b) Docstring
c) Interface
d) Modularity
4. ______ is a string literal denoted by triple quotes for providing the specifications of
certain program elements.
a) Interface
b) Modularity
c) Client
d) Docstring
Answer Key:-
1. b 2. c 3. a 4. d 5. c
6. d 7. a 8. b
OOPS principles:-
OOPS are the rules (or) guidelines which are supposed to be satisfied by any
programming language in order to call that programming language as OOPL.
Different oops principles are:-
1. Encapsulation
2. Polymorphism
3. Inheritance
4. Abstraction
Constructor Concept:-
Method Constructor
1. Name of method can be any name. 1. Constructor name should be always
__init__.
2. Method will be executed if we call that 2. Constructor will be executed
method. automatically at the time of object
creation.
3. Per object, method can be called any 3. Per object, Constructor will be executed
number of times. only once.
4. Inside method we can write business 4. Inside Constructor we have to declare
logic. and initialize instance variables.
Types of Variables:
Example Application:
class Employee:
def __init__(self):
self.eno=100
self.ename='John'
self.esal=10000
e=Employee()
print(e.__dict__)
Output:
Example Application:
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=Test()
t.m1()
print(t.__dict__)
Output:
{'a': 10, 'b': 20, 'c': 30}
Example Application:
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=Test()
t.m1()
t.d=40
print(t.__dict__)
Output {'a': 10, 'b': 20, 'c': 30, 'd': 40}
1. What is class?
Syntax:
class className:
''' documentation string '''
variables: instance variables, static and local variables
methods: instance methods, static methods, class methods
Documentation string represents description of the class. Within the class doc string is
always
optional. We can get doc string by using the following 2 ways.
1. print (classname.__doc__)
2. help (classname)
3. What is object?
Physical existence of a class is nothing but object. We can create any number of objects for a
class.
Syntax to create object: referencevariable = classname()
Example: s = Student()
The variable which can be used to refer object is called reference variable. By using
reference variable, we can access properties and methods of object.
Self variable:- self is the default variable which is always pointing to current object (like this
keyword in Java) By using self we can access instance variables and instance methods of
object.
Note:
1. self should be first parameter inside constructor
def __init__(self):
2. self should be first parameter inside instance methods
def talk(self):
Technical Tasks:-
Example Application:-
class Student:
'''''Developed by Brijesh for python demo'''
def __init__(self):
self.name='Brijesh'
self.age=40
self.marks=80
def talk(self):
print("Hello I am :",self.name)
print("My Age is:",self.age)
print("My Marks are:",self.marks)
st=Student()
st.talk()
O/P:-
Hello I am : Brijesh
My Age is : 40
My Marks are: 80
Example Application:- Write a Python program to create a Student class and Creates an
object to it. Call the method talk() to display student details.
class Student:
def __init__(self,name,rollno,marks):
self.name=name
self.rollno=rollno
self.marks=marks
def talk(self):
print("Hello My Name is:",self.name)
print("My Rollno is:",self.rollno)
print("My Marks are:",self.marks)
s1=Student("Brijesh",101,80)
s1.talk()
Output:
Hello My Name is: Brijesh
My Rollno is: 101
My Marks are: 80
Example Application:- Program to demonstrate constructor will execute only once per
object.
class Test:
def __init__(self):
print("Constructor execution...")
def m1(self):
print("Method execution...")
t1=Test()
t2=Test()
t3=Test()
t1.m1()
Output:
Constructor execution...
Constructor execution...
Constructor execution...
Method execution...
Example Application:-
class Student:
''''' This is student class with required data'''
def __init__(self,x,y,z):
self.name=x
self.rollno=y
self.marks=z
def display(self):
print("StudentName:{}\nRollno:{}\nMarks:{}".format(self.name,self.rollno,self.marks))
s1=Student("John",101,80)
s1.display()
s2=Student("Brown",102,100)
s2.display()
Output:
Student Name:John
Rollno:101
Marks:80
Student Name:Brown
Rollno:102
Marks:100
Example Application:-
class Employee:
def __init__(self):
self.eno=100
self.ename='John'
self.esal=10000
e=Employee()
print(e.__dict__)
Output:
Example Application:-
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t=Test()
t.m1()
print(t.__dict__)
Output:
Interview Questions:-
5. What is constructor?
Constructor is a special method which is used to initialize variables.
6. What is need of constructor?
Constructor call only once with one object.
7. What is class?
Class is a blueprint of object. Class is the collection of variables and methods.
8. What is object?
Object is a real world entity, which has its properties and functionalities.
9. What is difference between method and constructor?
Method Constructor
1. Name of method can be any name. 1. Constructor name should be always
__init__.
2. Method will be executed if we call that 2. Constructor will be executed
method. automatically at the time of object
creation.
3. Per object, method can be called any 3. Per object, Constructor will be executed
number of times. only once.
4. Inside method we can write business 4. Inside Constructor we have to declare
logic. and initialize instance variables.
1. _____ represents an entity in the real world with its identity and behaviour.
a) A method
b) An object
c) A class
d) An operator
4. What are the methods which begin and end with two underscore characters called?
a) Special methods
b) In-built methods
c) User-defined methods
d) Additional methods
Answer Key:-
1. B 2. b 3. a 4. a 5. d
Lecture – 6 (Inheritance in Python)
Inheritance:-
The concept of using properties of one class into another class without creating object of
that class explicitly is known as inheritance.
A class which is extended by another class is known as ‘super’ class.
A class which is extending another class is known as ‘sub’ class.
Both super class properties and sub class properties can be accessed through
subclass reference variable.
Super class properties directly we can use within the subclass.
Example Application:-
class x:
def m1(self):
self.i=1000
class y(x):
def m2(self):
self.j=2000
y1=y()
y1.m1()
y1.m2()
print (y1.i)
print (y1.j)
Output:-
1000
2000
Example Application:-
class x:
def m1(self):
self.i=1000
class y(x):
def m2(self):
self.j=2000
def display(self):
print self.i
print self.j
y1=y()
y1.m1()
y1.m2()
y1.display()
Output:-
1000
2000
Example Application:-
class parent:
parentAttr=100
def __init__(self):
print ('Calling parent constructor')
def parent_method(self):
print ('Calling parent method')
def setAttr(self,attr):
parent.parentAttr=attr
def getAttr(self):
print ('parent Attribute',parent.parentAttr)
class child(parent):
def __init__(self):
print ('Calling child constructor')
def child_method(self):
print ('Calling child method')
p=parent()
p.parent_method()
p.setAttr(200)
p.getAttr()
c=child()
c.child_method()
c.parent_method()
c.setAttr(300)
c.getAttr()
Output:-
Example Application:-
class x:
def __init__(self):
print 'in const of x'
class y(x):
def m1(self):
print 'in m1 of y'
y1=y()
y1.m1()
Output:-
in const of x
in m1 of y
Single Inheritance:- The concept of inheriting properties from only one class into another
class is known as single inheritance.
Example Application:-
class x:
def m1(self):
print('m1 of x')
class y(x):
def m2(self):
print('m2 of y')
y1=y()
y1.m1()
y1.m2()
Output:-
m1 of x
m2 of y
Multi-level Inheritance:- The concept of inheriting properties from multiple classes into
single class with the concept of ‘one after another’ is known as a multilevel inheritance.
Example Application:-
class x:
def m1(self):
print ('m1 of x')
class y(x):
def m2(self):
print ('m2 of y')
class z(y):
def m3(self):
print ('m3 of z')
z1=z()
z1.m1()
z1.m2()
z1.m3()
Output:-
m1 of x
m2 of y
m3 of z
Hierarchical Inheritance:- The concept of inheriting properties from one class into multiple
classes is known as a hierarchical inheritance.
Example Application:-
class x:
def m1(self):
print ('in m1 of x')
class y(x):
def m2(self):
print ('in m2 of y')
class z(x):
def m3(self):
print ('in m3 of z')
y1=y()
y1.m1()
y1.m2()
z1=z()
z1.m1()
z1.m3()
Output:-
in m1 of x
in m2 of y
in m1 of x
in m3 of z
Multiple Inheritance:- The concept of inheriting properties from multiple classes into single
class at a time is known as multiple inheritance.
Example Application:-
class x:
def m1(self):
print ('in m1 of x')
class y:
def m2(self):
print ('in m2 of y')
class z(x,y):
def m3(self):
print ('in m3 of z')
z1=z()
z1.m1()
z1.m2()
z1.m3()
y1=y()
y1.m2()
x1=x()
x1.m1()
Output:-
in m1 of x
in m2 of y
in m3 of z
in m2 of y
in m1 of x
Cyclic Inheritance:- The concept of inheriting the properties from subclass to superclass is
known as a cyclic inheritance. Python does not support cyclic inheritance.
Technical Tasks:-
class Rundog:
def bark(self):
print(“Sheru……………….”)
print(“Bho…bho…………”)
class Bulldog(Rundog):
def growl(self):
print(“Tommy……………”)
print(“Gurr.. gurr………”)
dog=Bulldog()
dog.bark()
dog.growl()
class Shape:
def setValue(self, s):
self.s=s
class Square(Shape):
def area(self):
return self.s*self.s
class Cube(Shape):
def volume(self):
return self.s*self.s*self.s
sq=Square()
x=int(input(“Enter side of square : ”))
a=sq.area()
print(“Area of square=”,a)
cu=Cube()
x=int(input(“Enter side of cube : ”))
v=cu.volume()
print(“Volume of cube=”,v)
class Employee:
def setEmployee(self,empid,empname):
self.empid=empid
self.empname=empname
def getEmployee(self):
print(“Employee Id=”,self.empid)
print(“Employee Name=”,self.empname)
class Payroll(Employee):
def setPayroll(self,bs,hra,da):
self.bs=bs
self.hra=hra
self.da=da
def getPayroll(self):
print(“Basic Salary=”,self.bs)
print(“House Rent Allowances=”,self.hra)
print(“Dearness Allowances=”,self.da)
class Loan:
def setLoan(self,amt):
self.amt=amt
class Payslip(Payroll,Loan):
def netSalary(self):
print(“Net Salary=”,self.bs+self.hra+self.da)
print(“Salary on hand=”,self.bs+self.hra+self.da-self.amt)
ps=Payslip()
empid=int(input(“Enter Employee Id : ”))
empname=input(“Enter Employee Name : ”)
ps.setEmployee(empid,empname)
bs=int(input(“Enter basic salary : ”))
hra=int(input(“Enter house rent allowances : ”))
da=int(input(“Enter dearness allowances : ”))
ps.setPayroll(bs,hra,da)
amt=int(input(“Enter monthly loan amt : ”))
ps.setLoan(amt)
print(“***************PAY SLIP******************”)
ps.getEmployee()
ps.getPayroll()
ps.netSalary()
Interview Questions:-
5. Which of the following represents a template, blueprint, or contract that defines objects
of the same type?
A. A class
B. An object
C. A method
D. A data field
7. Which of the following statements is most accurate for the declaration x = Circle()?
A. x contains an int value.
B. x contains an object of the Circle type.
C. x contains a reference to a Circle object.
D. You can assign an int value to x.
8. Which of the following statements can be used to check, whether an object “obj” is an
instance of class A or not?
A. obj.isinstance(A)
B. A.isinstance(obj)
C. isinstance(obj, A)
D. isinstance(A, obj)
Answer Key:-
1. A 2. a 3. c 4. b
5. a 6. a 7. c 8. c
Lecture – 7(Concept of Polymorphism and Exception Handling)
Polymorphism:-
Poly means many and morphs means forms.
Forms mean functionalities or logics.
The concept of defining multiple logics to perform some operation is known as a
polymorphism.
Polymorphism can be implemented in python by using method overriding.
Note:- Python does not support method overloading.
Method overriding:- The concept of defining multiple methods with the same name with
the same no. of parameters, one is in superclass and another in subclass is known as
method overriding.
Example Application:-
class parent:
def myMethod(self):
print ('Calling parent method')
class child(parent):
def myMethod(self):
print ('Calling child method')
c=child()
c.myMethod()
p=parent()
p.myMethod()
Output:-
Calling child method
Calling parent method
Output:-
parent altered
child before parent altered
parent altered
child after parent altered
Example Application:-
class x:
__p=1000
def m1(self):
print ('in m1 of x')
x1=x()
x1.m1()
print x.p
Output:-
in m1 of x
AttributeError: class x has no attribute 'p'
Example Application:-
class JustCounter:
__secretcount=0
def count(self):
self.__secretcount+=1
print self.__secretcount
counter=JustCounter()
counter.count()
counter.count()
Output:-
1
2
Eg 1:
x=10
if x==10
print("Hello")
SyntaxError: invalid syntax
Eg 2:
print "Hello"
SyntaxError: Missing parentheses in call to 'print'
Note:
Programmer is responsible to correct these syntax errors. Once all syntax errors are
corrected then only program execution will be started.
2. Runtime Errors:- Runtime Errors are also known as exceptions. While executing the
program if something goes wrong because of end user input or programming logic or
memory problems etc then we will get Runtime Errors.
What is Exception?
An unwanted and unexpected event that disturbs normal flow of program is called
exception.
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
Every exception in Python is an object. For every exception type the corresponding classes
are available. Whenever an exception occurs PVM will create the corresponding exception
object and will check for handling code. If handling code is not available then Python
interpreter terminates the program abnormally and prints corresponding exception
information to the console. The rest of the program won't be executed.
Eg:
print("Hello")
print(10/0)
print("Hi")
Output:-
Hello
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero
Without try-except:
print("stmt-1")
print(10/0)
print("stmt-3")
Output:
stmt-1
ZeroDivisionError: division by zero
Abnormal termination/Non-Graceful Termination
With try-except:
print("stmt-1")
try:
print(10/0)
except ZeroDivisionError:
print(10/2)
print("stmt-3")
Output:
stmt-1
5.0
stmt-3
Normal termination/Graceful Termination
Conclusions:
1. Within the try block if anywhere exception raised then rest of the try block wont be
executed even though we handled that exception. Hence we have to take only risky code
inside try block and length of the try block should be as less as possible.
2. In addition to try block, there may be a chance of raising exceptions inside except and
finally blocks also.
3. If any statement which is not part of try block raises an exception then it is always
abnormal termination.
Example Application:-
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError :
print("Can't Divide with Zero")
except ValueError:
print("please provide int value only")
Output 1:-
Enter First Number: 10
Enter Second Number: 2
5.0
Output 2:-
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
Output 3:-
Enter First Number: 10
Enter Second Number: ten
please provide int value only
If try with multiple except blocks available then the order of these except blocks is
important. Python interpreter will always consider from top to bottom until matched except
block identified.
Example Application:-
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ArithmeticError :
print("ArithmeticError")
except ZeroDivisionError:
print("ZeroDivisionError")
Output:-
Enter First Number : 10
Enter Second Number : 0
ArithmeticError
Example Application:-
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except (ZeroDivisionError,ValueError) as msg:
print("Plz Provide valid numbers only and problem is: ",msg)
Output 1:-
Enter First Number: 10
Enter Second Number: 0
Plz Provide valid numbers only and problem is: division by zero
Output 2:-
Enter First Number: 10
Enter Second Number: ten
Plz Provide valid numbers only and problem is: invalid literal for int() with base 10: 'ten'
Output 1:-
Enter First Number: 10
Enter Second Number: 0
ZeroDivisionError:Can't divide with zero
Output 2:-
Enter First Number: 10
Enter Second Number: ten
Default Except:Plz provide valid input only
Re-writing of base class method into derived class is called method overriding.
2. What is exception?
try:
# Code which you want to protect
except ExceptionName:
# Code to handle exception
finally:
# Code which you want to execute always
Technical Tasks:-
class parent:
def myMethod(self):
print('Calling parent method‘)
class child(parent):
def myMethod(self):
print('Calling child method‘)
c=child()
c.myMethod()
p=parent()
p.myMethod()
try:
x=int(input("Enter first no : "))
y=int(input("Enter second no : "))
z=x/y
print("Result=",z)
except ValueError:
print("Enter numbers only")
except ZeroDivisionError:
print("Are you trying to / by zero?")
finally: #Optional
print("Bye...Bye...")
Interview Questions:-
1. What is Polymorphism?
The term Polymorphism means one thing many forms.
2. What is method overriding?
Rewriting of base class method into derived class is called method overriding.
3. What is exception?
The dictionary meaning of exception is abnormal termination. When exception is
occurred program is terminated abnormally and rest of code is not executed.
4. What is exception handling?
Exception handling is a mechanism to handle exception to achieve normal execution
of program.
5. Explain try, except and finally blocks.
try:
# Code which you want to protect
except:
# Code which is used to handle exception
finally:
# Code which you want to execute always
3. Overriding means changing behaviour of methods of derived class methods in the base
class.
a) True
b) False
Answer Key:-
1. d 2. c 3. b 4. a
Answer Key:-
1. c 2. c 3. c 4. c
String is a sequence of characters. This is a widely used data type in projects. Python has
several built-in functions associated with the string data type. These functions let us easily
modify and manipulate strings. We can think of functions as being actions that we perform
on elements of our code. Built-in functions are those that are defined in the Python
programming language and are readily available for us to use.
The functions str.upper() and str.lower() will return a string with all the letters of an original
string converted to upper- or lower-case letters. Because strings are immutable data types,
the returned string will be a new string. Any characters in the string that are not letters will
not be changed.
For Example:-
ss=“Softpro India”
print(ss.upper())
O/P:-
SOFTPRO INDIA
Example Application:-
"""
Develop a program in python to take a string as input now display string in upper case
and lowercase also find the length of string.
"""
st=input("Enter a string : ")
print("String in upper case : ",st.upper())
print("String in lower case : ",st.lower())
print("The length of string : ",len(st)) # The len() method find the length of string
The str.join(), str.split(), and str.replace() methods are a few additional ways to manipulate
strings in Python.
The str.join() method will concatenate two strings, but in a way that passes one
string through another.
The str.split() method returns a list of strings that are separated by whitespace if no
other parameter is given.
The str.replace() method can take an original string and return an updated string
with some replacement.
Technical Tasks:-
1. Develop a program in python to check given string is palindrome or not.
2. Develop a program in python to take user full name as input and display short
name.
4. Develop a program in python to take a decimal no. as input and display its binary,
octal and hexa-decimal equivalent.
print('{0:.2}'.format(1/3))
a) 0.333333
b) 0.33
c) 0.333333:.2
d) Error
print('{0:.2%}'.format(1/3))
a) 0.33
b) 0.33%
c) 33.33%
d) 33%
print('ab12'.isalnum())
a) True
b) False
c) None
d) Error
print('ab,12'.isalnum())
a) True
b) False
c) None
d) Error
print('ab'.isalpha())
a) True
b) False
c) None
d) Error
print('a B'.isalpha())
a) True
b) False
c) None
d) Error
print('0xa'.isdigit())
a) True
b) False
c) None
d) Error
print(''.isdigit())
a) True
b) False
c) None
d) Error
print('my_string'.isidentifier())
a) True
b) False
c) None
d) Error
print('abc'.islower())
a) True
b) False
c) None
d) Error
Answer Key:-
1. B 2. c 3. a 4. b 5. a
6. b 7. b 8. b 9. a 10. a