Python Lab
Python Lab
Name:
HT. No:
Depart of Mathematics
Osmania University
Hyderabad
Python Lab [CS205P] Date: |0 |2017
Index
S. No. Program Page No. Date
Introduction to Python Programming
Print Function and Data Types
Program to display the following information: Your name, Full
01 04 – – 2017
Address, Mobile Number, College Name, Course Subjects
Control Structures, Lists
02 Program to find the largest three integers using if-else 05 – – 2017
Program that receives a series of positive numbers and display
03 06 – – 2017
the numbers in order and their sum
04 Program to find the product of two matrices [A]mxp and [B]pxr 07 – – 2017
Program to display two random numbers that are to be added,
the program should allow the student to enter the answer.
If the answer is correct, a message of congratulations
05 08 – – 2017
should be displayed.
If the answer is incorrect, the correct answer should be
displayed.
Functions and Recursion
Write recursive and non-recursive functions for the following
To find GCD of two integers 09 – – 2017
06 To find the factorial of positive integer 10 – – 2017
To print Fibonacci Sequence up to given number n 11 – – 2017
To display prime number from 2 to n. 12 – – 2017
Function that accepts two arguments: a list and a number n. It
07 13 – – 2017
displays all of the numbers in the list that are greater than n
Functions that accept a string as an argument and return the
08 14 – – 2017
number of vowels and consonants that the string contains
Files, Exceptions, Lists, Sets, random numbers
Program to write a series of random numbers in a file from 1
09 15 – – 2017
to n and display.
Program to write the content in a file and display it with a line
10 16 – – 2017
number followed by a colon
11 Program to display a list of all unique words in a text file 17 – – 2017
12 Program to analyze the two text files using set operations 18 – – 2017
Object Oriented Programming
13 Program to implement the inheritance 20 – – 2017
14 Program to implement the polymorphism 26 – – 2017
GUI Programming
15 Program that converts temperature from Celsius to Fahrenheit 27 – – 2017
16 Program that displays your details when a button is clicked 29 – – 2017
Dept. of Mathematics–OU 1
Python Lab [CS205P] Date: |0 |2017
Introduction to Python Programming
Before you can run Python programs on your computer, you need to download and install
the Python interpreter from www.python.org/download.
When the installer is finished, the Python interpreter, the IDLE programming environment,
and the Python documentation will be installed on your system.
IDLE (Python GUI) — when click this item, the IDLE programming environment will
execute. IDLE is an integrated development environment (IDE) that we can use to create,
edit, and execute Python programs.
Python Command Line — this item launches the Python interpreter in interactive mode.
Python Manuals — this item opens the Python Manuals in web browser. The manuals
include tutorials, a reference section for the Python standard library, an in-depth
reference for the Python language, and information on many advanced topics.
Module Docs — this item launches a utility program that allows us to browse
documentation for the modules in the Python standard library.
Uninstall Python — this item removes Python from your system.
The Python Interpreter
The Python interpreter is a program that can read Python program statements and execute
them.
You can use the interpreter in two modes: interactive mode (line) and script (file) mode.
In interactive mode, the interpreter waits for you to type Python statements on the
keyboard.
Once you type a statement, the interpreter executes it and then waits for you to type
another.
In script mode, the interpreter reads the contents of a file that contains Python
statements.
Such a file is known as a Python program or a Python script.
The interpreter executes each statement in the Python program as it reads it.
If you plan to execute the Python interpreter from a command prompt window, you will
probably want to add the Python directory to the existing contents of your system’s Path
variable (like java).
The IDLE is an IDE that combines several development tools into one program, including:
A Python Shell running in interactive mode. We can type Python statements at the shell
prompt and immediately execute them. We can also run complete Python programs.
A Text Editor that color codes Python keywords and other parts of programs.
A “Check Module” tool that checks a Python program for syntax errors without running the
program.
Search tools that allow us to find text in one or more files.
Text formatting tools that help us maintain consistent indentation levels in a Python
program.
A Debugger that allows us to single-step through a Python program and watches the
values of variables change as each statement executes.
Several other advanced tools for developers.
The >>> prompt indicates that the interpreter is waiting for you to type a Python statement.
When you type a statement at the >>> prompt and press the Enter key, the statement is
executed.
Dept. of Mathematics–OU 2
Python Lab [CS205P] Date: |0 |2017
Code that is typed into the editor window or in the Python Shell window, is colorized as
follows:
Python keywords are displayed in orange.
Comments are displayed in red.
String literals are displayed in green.
Defined names, such as the names of functions and classes, are displayed in blue.
Built-in functions are displayed in purple.
You can change IDLE’s colour settings by clicking Options on the menu bar, then clicking
Configure IDLE. Select the Highlighting tab at the top of the dialog box, and you can specify
colours for each element of a Python program.
The IDLE editor has Automatic Indentation feature. By default, IDLE indents four spaces for
each level of indentation (possible to change the number of spaces for indentation).
The python program files are saved with .py extension.
Once you have typed a program into the editor, you can run it by pressing the F5 key or by
clicking Run on the editor window’s menu bar, then Run Module.
When the program runs you will see its output displayed in IDLE’s Python Shell window.
If a program contains a syntax error, when you run the program you will see the dialog box.
After you click the OK button, the editor will highlight the location of the error in the code.
If you want to check the syntax of a program without trying to run it, you can click Run on
the menu bar, then Check Module. Any syntax errors that are found will be reported.
Comments
Comments are notes of explanation that document lines or sections of a program.
Comments are part of the program, but the Python interpreter ignores them.
They are intended for people who may be reading the source code, not the computer.
In Python, comments begin with the # character. When the Python interpreter sees a # character, it
ignores everything from that character to the end of the line.
Example, # this program displays the person’s details.
Programmers commonly write end-line comments in their code.
An end-line comment is a comment that appears at the end of a line of code.
It usually explains the statement that appears in that line.
Each line ends with a comment that briefly explains what the line does.
Example, print('123 Full Circle Drive') # Display the address.
Dept. of Mathematics–OU 3
Python Lab [CS205P] Date: |0 |2017
# Write a program that displays the following information:
# Your name, Full address, Mobile number, College name, Course subjects.
Output:
Enter your details
Name: Manjulatha
Address: 1-8-39/B Chikkadpally Hyderabad 500020
Mobile Number: 900033533
College Name: Osmania University
Course Name: M.Sc. Computer Science
My personal details are
Manjulatha
1-8-39/B Chikkadpally Hyderabad 500020
900033533
Osmania University
M.Sc. Computer Science
Course Subjects are
Python
Computer Networks
Design and Analysis of Algorithm
Automata Theory
Dept. of Mathematics–OU 4
Python Lab [CS205P] Date: |0 |2017
# Write a program to find the largest three integers using if-else
if x>y :
if x>z :
large = x
else :
large = z
else :
if y>z :
large = y
else :
large = z
Output:
Enter any three integers
Enter first integer 12
Enter second integer 16
Enter third integer 8
Largest of entered three integers is 16
Dept. of Mathematics–OU 5
Python Lab [CS205P] Date: |0 |2017
# Write a program that asks the user to enter a series of positive numbers
# The user should enter a negative number to signal the end of the series
# and the program should display the numbers in order and their sum.
import random
total = 0
series = []
keep_going = 'y'
Output:
Enter a series of positive numbers
Enter a negative number to signal the end of the series
8
2
4
6
3
-1
Entered series is [2, 3, 4, 6, 8]
Sum of series is 23
Entered series in reverse order is [8, 6, 4, 3, 2]
Dept. of Mathematics–OU 6
Python Lab [CS205P] Date: |0 |2017
# Write a program to find the product of two matrices [A]mxp and [B]pxr
import random
Output:
Enter the values of m, p, r
2
2
2
Enter the elements of matrix A
1
2
3
4
Enter the elements of matrix B
1
0
0
1
The product of matrices A and B is
1
2
3
4
Dept. of Mathematics–OU 7
Python Lab [CS205P] Date: |0 |2017
# Write a program to display two random numbers that are to be added,
# the program should allow the student to enter the answer.
# If the answer is correct, a message of congratulations should be displayed.
# If the answer is incorrect, a message showing the correct answer.
import random
if sum==z :
print('Congratulations, you have entered correct answer')
elif sum>z :
print('You have entered low number')
print('Correct answer is',sum)
else :
print('You have entered high number')
print('Correct answer is',sum)
Output:
Addition of two random integers between 0 and 1000
Enter your guess 1400
You have entered high number
Correct answer is 817
>>>
Addition of two random integers between 0 and 1000
Enter your guess 722
You have entered low number
Correct answer is 773
Dept. of Mathematics–OU 8
Python Lab [CS205P] Date: |0 |2017
# Write a program to find the GCD of two positive integers
def main():
print('Enter any two positive integers')
m = int(input())
n = int(input())
gcd_rec(m, n)
gcd_nonrec(m, n)
Output:
Enter any two positive integers
12
4
Rec: GCD of given integers is 4
Non-Rec: GCD of given integers is 4
>>>
Enter any two positive integers
12
7
Rec: GCD of given integers is 1
Non-Rec: GCD of given integers is 1
Dept. of Mathematics–OU 9
Python Lab [CS205P] Date: |0 |2017
# Write a program to find the factorial positive integer
def main():
n = int(input('Enter a positive integer '))
print('Rec: Factorial value is',fact_rec(n))
print('Non-Rec: Factorial value is',fact_nonrec(n))
Output:
Enter a positive integer 4
Rec: Factorial value is 24
Non-Rec: Factorial value is 24
>>>
Enter a positive integer 6
Rec: Factorial value is 720
Non-Rec: Factorial value is 720
Dept. of Mathematics–OU 10
Python Lab [CS205P] Date: |0 |2017
# Write a program to print Fibonacci sequence up to given number n
def main():
n = int(input('How many terms do you want '))
Output:
How many terms do you want 6
Rec: Fibonacci series is
0
1
1
2
3
5
Non_Rec: Fibonacci series is
0
1
1
2
3
5
Dept. of Mathematics–OU 11
Python Lab [CS205P] Date: |0 |2017
# Write recursive and non-recursive functions to display prime numbers from 2 to n
def main():
n = int(input('Enter a positive integer '))
Output:
Enter a positive integer 10
Rec: Prime numbers are
2
3
5
7
Non_Rec: Prime numbers are
2
3
5
7
Dept. of Mathematics–OU 12
Python Lab [CS205P] Date: |0 |2017
# Write a function that accepts two arguments: a list and a number n.
# The function displays all of the numbers in the list that are greater than n.
def main() :
print('Enter a list of positive numbers')
print('Enter a negative number to signal the end of the list')
numbers = []
keep_going = 'y'
while keep_going == 'y' :
x = int(input())
if x>=0 :
numbers.append(x)
else :
keep_going = 'n'
# Function definition
def display_list(given_list, n) :
for num in given_list :
if num>n :
print(num)
Output:
Enter a list of positive numbers
Enter a negative number to signal the end of the list
2
4
9
5
6
7
1
8
-1
Enter the value of n 4
Display the numbers in the list
9
5
6
7
8
Dept. of Mathematics–OU 13
Python Lab [CS205P] Date: |0 |2017
# Write a function that accepts a string as an argument and
# returns the no. of vowels that the string contains.
# Another function to return number of consonants.
def main() :
str_in = input('Enter a string ')
str_lower = str_in.lower()
vow = 'aeiou'
Output:
Enter a string Computer Science
Number of vowels in a given string is 6
Number of consonants in a given string is 9
>>>
Enter a string Programming in Python
Number of vowels in a given string is 5
Number of consonants in a given string is 14
Dept. of Mathematics–OU 14
Python Lab [CS205P] Date: |0 |2017
# Write a series of random numbers to a file from 1 to n and display.
import random
try :
# open file in write mode
fp = open('msc.txt','w')
for i in range(n) :
num = random.randrange(1, n)
fp.write(str(num)+' ')
fp.close()
except IOError :
print('There is an error in file operations')
sys.exit()
try :
# Open file in read mode
fp = open('msc.txt','r')
print(fp.read())
fp.close()
except IOError :
print('There is an error in file operations')
sys.exit()
Output:
Enter the value of n 10
Name of the file is msc.txt
The series of random numbers are
4552388941
>>>
Enter the value of n 20
Name of the file is msc.txt
The series of random numbers are
2 10 3 12 17 18 5 18 18 14 5 2 11 14 8 1 14 17 8 14
Dept. of Mathematics–OU 15
Python Lab [CS205P] Date: |0 |2017
# Write a program to create file, write the content
# and display the contents of the file with each line
# preceded with a line number (start with 1) followed by a colon.
line = ''
while line != 'end' :
line = input();
fp.write(line+'\n')
fp.close()
except IOError :
print('There is an error in file operations')
sys.exit()
line = fp.readline()
line_no = 1;
while line != '' :
print(line_no,':',line)
line_no = line_no+1
line = fp.readline()
fp.close()
except IOError :
print('There is an error in file operations')
sys.exit()
Output:
Entered the content in the file
and "end" signal the end of content
how
are
you
friends
end
Display the content of file
1 : how
2 : are
3 : you
4 : friends
5 : end
Dept. of Mathematics–OU 16
Python Lab [CS205P] Date: |0 |2017
# Write a program that opens a specified text file and
# then displays a list of all the unique words found in the file.
# Store each word as an element of a set.
try :
# open a text file in read mode
fp = open('msc.txt','r')
myset = set('')
repeat = set('')
while True :
line = fp.readline()
if line == '' :
break
else :
wordlist = line.split()
for word in wordlist :
if word in myset :
repeat.add(word)
else :
myset.add(word)
fp.close()
except IOError :
print('There is an error in file operations')
sys.exit()
unique = myset.difference(repeat)
print(unique)
Output:
{'to', 'msc', 'regular', 'college', 'year', 'and', 'good', 'first', 'bhargavi', 'science', 'computer'}
Note: Save the above text file with file name msc.txt in the current directory or where the program files
are saved.
Dept. of Mathematics–OU 17
Python Lab [CS205P] Date: |0 |2017
# Write a program to analyze the contents of two text files
# using set operations (union, intersection, difference).
try :
fp1 = open('first.txt','r')
myset1 = set('')
repeat1 = set('')
while True :
line = fp1.readline()
if line == '' :
break
else :
wordlist = line.split()
for word in wordlist :
if word in myset1 :
repeat1.add(word)
else :
myset1.add(word)
fp1.close()
except IOError :
print('There is an error in file operations')
sys.exit()
try :
fp2 = open('second.txt','r')
myset2 = set('')
repeat2 = set('')
while True :
line = fp2.readline()
if line == '' :
break
else :
wordlist = line.split()
for word in wordlist :
if word in myset2 :
repeat2.add(word)
else :
myset2.add(word)
fp2.close()
except IOError :
print('There is an error in file operations')
sys.exit()
Output:
In first file
Repeated word list :
{'student', 'i', 'am'}
Unique word list :
{'year', 'msc', 'and', 'bhargavi', 'first', 'regular', 'to', 'good', 'science', 'computer', 'college'}
In second file
Repeated word list :
{'student', 'i', 'am'}
Unique word list :
{'year', 'learning', 'msc', 'and', 'irregular', 'second', 'to', 'science', 'slow', 'ashia', 'computer', 'college'}
Comparing first file and second file
Repeated word list :
{'i', 'student', 'am'}
Unique word list :
{'regular', 'bhargavi', 'first', 'good'}
Common word list :
{'year', 'msc', 'and', 'to', 'science', 'computer', 'college'}
File name: first.txt
i am bhargavi
msc computer science first year student
i am regular to college and good student
Note: Save the above text files with file names first.txt and second.txt in the current directory or where
the program files are saved.
Dept. of Mathematics–OU 19
Python Lab [CS205P] Date: |0 |2017
# Write a program to implement the single inheritance
# defining class A
class A :
# The _ _init_ _method initializes data
def __init__(self, a) :
self.__a = a
def set_a(self, a) :
self.__a = a
def get_a(self) :
return self.__a
def set_b(self, b) :
self.__b = b
def get_b(self) :
return self.__b
def main() :
# Create an object for the class B.
obj = B(10, 20)
Output:
A: a = 10
B: b = 20
Dept. of Mathematics–OU 20
Python Lab [CS205P] Date: |0 |2017
# Write a program to implement the multilevel inheritance
class A :
# The _ _init_ _method initializes data
def __init__(self, a) :
self.__a = a
def set_a(self, a) :
self.__a = a
def get_a(self) :
return self.__a
class B(A) :
def set_b(self, b) :
self.__b = b
def get_b(self) :
return self.__b
def set_c(self, c) :
self.__c = c
def get_c(self) :
return self.__c
def main() :
obj = C(10,20,30)
print('A: a =',obj.get_a())
print('B: b =',obj.get_b())
print('C: c =',obj.get_c())
Dept. of Mathematics–OU 21
Python Lab [CS205P] Date: |0 |2017
# Write a program to implement the hierarchical inheritance
class A :
def __init__(self, a) :
self.__a = a
def set_a(self, a) :
self.__a = a
def get_a(self) :
return self.__a
class B(A) :
def set_b(self, b) :
self.__b = b
def get_b(self) :
return self.__b
class C(A) :
def set_c(self, c) :
self.__c = c
def get_c(self) :
return self.__c
def main() :
obj1 = B(10,20)
print('A: a =',obj1.get_a())
print('B: b =',obj1.get_b())
obj2 = C(30,40)
print('A: a =',obj2.get_a())
print('C: c =',obj2.get_c())
main()
Output:
A: a = 10
B: b = 20
A: a = 30
C: c = 40
Dept. of Mathematics–OU 22
Python Lab [CS205P] Date: |0 |2017
# Write a program to implement the multiple inheritance
class A :
def __init__(self, a) :
self.__a = a
def set_a(self, a) :
self.__a = a
def get_a(self) :
return self.__a
class B :
def set_b(self, b) :
self.__b = b
def get_b(self) :
return self.__b
def set_c(self, c) :
self.__c = c
def get_c(self) :
return self.__c
def main() :
obj = C(10,20,30)
print('A: a =',obj.get_a())
print('B: b =',obj.get_b())
print('C: c =',obj.get_c())
main()
Output:
A: a = 10
B: b = 20
C: c = 30
Dept. of Mathematics–OU 23
Python Lab [CS205P] Date: |0 |2017
# Write a program to implement the hybrid inheritance
class A :
def __init__(self, a) :
self.__a = a
def set_a(self, a) :
self.__a = a
def get_a(self) :
return self.__a
class B(A) :
def set_b(self, b) :
self.__b = b
def get_b(self) :
return self.__b
class C(A) :
def set_c(self, c) :
self.__c = c
def get_c(self) :
return self.__c
class D(B,C) :
def set_d(self, d) :
self.__d = d
def get_d(self) :
return self.__d
Dept. of Mathematics–OU 24
Python Lab [CS205P] Date: |0 |2017
def main() :
obj = D(10,20,30,40)
print('A: a =',obj.get_a())
print('B: b =',obj.get_b())
print('C: c =',obj.get_c())
print('D: d =',obj.get_d())
Output:
A: a = 10
B: b = 20
C: c = 30
D: d = 40
Dept. of Mathematics–OU 25
Python Lab [CS205P] Date: |0 |2017
# Write a program to implement the polymorphism
def stop(self) :
raise NotImplementedError
def drive(self) :
return 'Sports car driving'
def stop(self) :
return 'Sports car stopping'
class Truckcar(Car) :
def drive(self) :
return 'Truck car driving'
def stop(self) :
return 'Truckc ar stopping'
Output:
x : Sports car driving
x : Sportsc ar stopping
y : Truck car driving
y : Truck car stopping
z : Sports car driving
z : Sports car stopping
Dept. of Mathematics–OU 26
Python Lab [CS205P] Date: |0 |2017
# Write a GUI program that converts temperature from Celsius to Fahrenheit
import tkinter
class CConverttoF:
def __init__(self):
# Create the main window widget.
self.main_window = tkinter.Tk()
self.prompt_label.pack(side='left')
self.celsius_entry.pack(side='left')
self.descr_label = tkinter.Label(self.mid_frame,
text='Converted to Fahrenheit ')
self.value = tkinter.StringVar()
self.fahrenheit_label = tkinter.Label(self.mid_frame,
textvariable = self.value)
self.descr_label.pack(side='left')
self.fahrenheit_label.pack(side='left')
Dept. of Mathematics–OU 27
Python Lab [CS205P] Date: |0 |2017
# Convert temperature from Celsius to Fahrenheit
def convert(self):
self.C = float(self.celsius_entry.get())
self.F = 9/5*(self.C)+32
self.value.set(self.F)
Output:
Dept. of Mathematics–OU 28
Python Lab [CS205P] Date: |0 |2017
# Write a GUI program that displays your details when a button is clicked
import tkinter
class Details:
def __init__(self):
# Create the main window widget.
self.main_window = tkinter.Tk()
self.name_label.pack(side='left')
self.name_entry.pack(side='left')
self.addr_label.pack(side='left')
self.addr_entry.pack(side='left')
self.name1_label.pack(side='left')
self.name2_label.pack(side='left')
self.addr1_label.pack(side='left')
self.addr2_label.pack(side='left')
Dept. of Mathematics–OU 29
Python Lab [CS205P] Date: |0 |2017
Output:
Dept. of Mathematics–OU 30