0% found this document useful (0 votes)
6 views31 pages

Python Lab

The document outlines a Python Lab course for M.Sc. Computer Science students, detailing various programming exercises and concepts including data types, control structures, functions, recursion, file handling, and object-oriented programming. Each section includes specific programs to be implemented, such as finding the largest integers, calculating GCD, and matrix multiplication. It also provides instructions for setting up the Python environment and using the IDLE programming interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views31 pages

Python Lab

The document outlines a Python Lab course for M.Sc. Computer Science students, detailing various programming exercises and concepts including data types, control structures, functions, recursion, file handling, and object-oriented programming. Each section includes specific programs to be implemented, such as finding the largest integers, calculating GCD, and matrix multiplication. It also provides instructions for setting up the Python environment and using the IDLE programming interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Python Lab

M. Sc. [Computer Science]


I Year II Semester

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.

print('Enter your details')


name = input('Name: ')
address = input('Address: ')
mobile_number = input('Mobile Number: ')
college_name = input('College Name: ')
course_name = input('Course Name: ')

print('My personal details are')


print(name)
print(address)
print(mobile_number)
print(college_name)
print(course_name)

print('Course Subjects are')


print('\t Python')
print('\t Computer Networks')
print('\t Design and Analysis of Algorithm')
print('\t Automata Theory')

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

print('Enter any three integers ')


x = int(input('Enter first integer '))
y = int(input('Enter second integer '))
z = int(input('Enter third integer '))

if x>y :
if x>z :
large = x
else :
large = z
else :
if y>z :
large = y
else :
large = z

print('Largest of entered three integers is',large)

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

print('Enter a series of positive numbers')


print('Enter a negative number to signal the end of the series')

total = 0
series = []
keep_going = 'y'

while keep_going == 'y' :


x = int(input()) # reading input and convert to integer

# check for the given number is negative


if x>=0 :
total = total+x
series.append(x) # add new number to the list
else :
keep_going = 'n'

# Sorting list of elements in order


series.sort()
print('Entered series is',series)
print('Sum of series is',total)

# Reversing list of elements


series.reverse()
print('Entered series in reverse order is',series)

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

print('Enter the values of m, p, r ')


m = int(input())
p = int(input())
r = int(input())

A = [[random.random()for row in range(m)]for col in range(p)]


B = [[random.random()for row in range(p)]for col in range(r)]
C = [[random.random()for row in range(m)]for col in range(r)]

print('Enter the elements of matrix A ')


for i in range(m):
for j in range(p):
A[i][j] = int(input())

print('Enter the elements of matrix B ')


for i in range(p):
for j in range(r):
B[i][j] = int(input())

print('The product of matrices A and B is ')


for i in range(m):
for j in range(r):
C[i][j]=0
for k in range(p):
C[i][j] = C[i][j]+A[i][k]*B[k][j]
print(C[i][j])

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

print('Addition of two random integers between 0 and 1000')


x = random.randrange(1000)
y = random.randrange(1000)
sum = x+y
z = int(input('Enter your guess '))

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)

# Define Recursive function


def gcd_rec(x, y):
if y==0 :
print('Rec: GCD of given integers is',x)
else:
gcd_rec(y, x%y)

# Define Non-recursive function


def gcd_nonrec(x, y):
while x%y!=0 :
r = x%y
x = y
y = r
print('Non-Rec: GCD of given integers is',y)

# Call main function


main()

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

# Define Recursive function


def fact_rec(x):
if x==1:
return 1
else:
return x*fact_rec(x-1)

# Define Non-recursive function


def fact_nonrec(x):
fact = 1
for i in range(1, x+1):
fact = fact*i
return fact

# Call main function


main()

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

print('Rec: Fibonacci series is')


for i in range(n):
print(fib_rec(i))

print('Non_Rec: Fibonacci series is ')


fib_nonrec(n)

# Define Recursive function


def fib_rec(x):
if x==0:
return 0
elif x==1:
return 1
else:
return fib_rec(x-1)+fib_rec(x-2)

# Define Non-recursive function


def fib_nonrec(x):
f1 = 0
f2 = 1
print(f1)
print(f2)
for i in range(2, x):
f3 = f2+f1
print(f3)
f1 = f2
f2 = f3

# Call main function


main()

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

print('Rec: Prime numbers are')


for i in range(2, n+1):
if prime_rec(2, i, 2)!=0:
print(i)

print('Non_Rec: Prime numbers are')


for i in range(2, n+1):
if prime_nonrec(i)!=0:
print(i)

# Define Recursive function


def prime_rec(fact, x, y):
if (fact==2)&(x==y):
return x
elif x%y==0:
return prime_rec(fact+1, x, y+1)
elif fact>2:
return 0
else:
return prime_rec(fact, x, y+1)

# Define Non-recursive function


def prime_nonrec(x):
for i in range(2, x):
if x%i==0:
return 0

# Call main function


main()

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'

n = int(input('Enter the value of n '))


print('Display the numbers in the list')
display_list(numbers, n)

# Function definition
def display_list(given_list, n) :
for num in given_list :
if num>n :
print(num)

# Calling main function


main()

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'

num = vowels(str_lower, vow)


print('Number of vowels in a given string is',num)

num = consonants(str_lower, vow)


print('Number of consonants in a given string is',num)

# defining a function to find number of vowels in a string


def vowels(string, vow) :
count = 0
for x in string :
if x in vow :
count = count+1
return count

# defining a function to find number of consonants in a string


def consonants(string, vow) :
count = 0
for x in string :
if x not in vow and x!=' ' :
count = count+1
return count

# calling main method


main()

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

n = int(input('Enter the value of n '))

try :
# open file in write mode
fp = open('msc.txt','w')

print('Name of the file is',fp.name)

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.

print('Entered the content in the file')


print('and "end" signal the end of content')
try :
fp = open('sample.txt','w')

line = ''
while line != 'end' :
line = input();
fp.write(line+'\n')

fp.close()
except IOError :
print('There is an error in file operations')
sys.exit()

print('Display the content of file')


try :
fp = open('sample.txt','r')

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

File name: msc.txt


i am bhargavi
msc computer science first year student
i am regular to college and good student

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

print('In first file')


print('Repeated word list :\n',repeat1)
Dept. of Mathematics–OU 18
Python Lab [CS205P] Date: |0 |2017
print('Unique word list :')
unique1 = myset1.difference(repeat1)
print(unique1)

print('In second file')


print('Repeated word list :\n',repeat2)
print('Unique word list :')
unique2 = myset2.difference(repeat2)
print(unique2)

print('Comparing first file and second file')


print('Repeated word list :'),
repeat = repeat1.union(repeat2)
print(repeat)
print('Unique word list :')
unique = unique1.difference(unique2)
print(unique)
print('Common word list :')
common = unique1.intersection(unique2)
print(common)

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

File name: second.txt


i am ashia
msc computer science second year student
i am irregular to college and slow learning 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

# Defining class B. It is a subclass of class A


class B(A) :

def __init__(self, a, b):


# Call the superclass's _ _init_ _ method and pass the required
arguments.
A.__init__(self, a)
self.__b = b

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)

# Display the data.


print('A: a =',obj.get_a())
print('B: b =',obj.get_b())

# Call the main function


main()

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 __init__(self, a, b):


A.__init__(self, a)
self.__b = b

def set_b(self, b) :
self.__b = b

def get_b(self) :
return self.__b

# Defining class C. It is a subclass of class B


class C(B) :

def __init__(self, a, b, c):


B.__init__(self, a, b)
self.__c = c

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

# Call the main function


main()
Output:
A: a = 10
B: b = 20
C: c = 30

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 __init__(self, a, b):


A.__init__(self, a)
self.__b = b

def set_b(self, b) :
self.__b = b

def get_b(self) :
return self.__b

class C(A) :

def __init__(self, a, c):


A.__init__(self, a)
self.__c = c

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 __init__(self, b):


self.__b = b

def set_b(self, b) :
self.__b = b

def get_b(self) :
return self.__b

# Defining class C. It is a subclass of classes A and B


class C(A,B) :

def __init__(self, a, b, c):


A.__init__(self, a)
B.__init__(self, b)
self.__c = c

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 __init__(self, a, b):


A.__init__(self, a)
self.__b = b

def set_b(self, b) :
self.__b = b

def get_b(self) :
return self.__b

class C(A) :

def __init__(self, a, c):


A.__init__(self, a)
self.__c = c

def set_c(self, c) :
self.__c = c

def get_c(self) :
return self.__c

class D(B,C) :

def __init__(self, a, b, c, d):


B.__init__(self, a, b)
C.__init__(self, a, c)
self.__d = d

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

# Call the main function


main()

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

# Defining abstract class


class Car :
def __init__(self, name) :
self.name = name

# Defining abstract method


def drive(self) :
raise NotImplementedError

def stop(self) :
raise NotImplementedError

# Defining concrete class


class Sportscar(Car) :

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'

cars = [Sportscar('x'), Truckcar('y'), Sportscar('z')]


for car in cars :
print(car.name,':',car.drive())
print(car.name,':',car.stop())

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

# Create frame on window


self.top_frame = tkinter.Frame(self.main_window)
self.mid_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)

# Create the widgets for the top frame.


self.prompt_label = tkinter.Label(self.top_frame,
text = 'Enter temparature in Celsius ')
self.celsius_entry = tkinter.Entry(self.top_frame, width = 10)

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

# Create the button


self.calc_button = tkinter.Button(self.bottom_frame,
text = 'Convert',
command = self.convert)
self.quit_button = tkinter.Button(self.bottom_frame,
text = 'Quit',
command = self.main_window.destroy)
# Pack the buttons.
self.calc_button.pack(side='left')
self.quit_button.pack(side='left')

# Pack the frames.


self.top_frame.pack()
self.mid_frame.pack()
self.bottom_frame.pack()

# Enter the tkinter main loop.


tkinter.mainloop()

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)

# Create an instance of the CConverttoF class.


obj = CConverttoF()

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

# Create frame on window


self.frame1 = tkinter.Frame(self.main_window)
self.frame2 = tkinter.Frame(self.main_window)
self.frame3 = tkinter.Frame(self.main_window)
self.frame4 = tkinter.Frame(self.main_window)
self.frame5 = tkinter.Frame(self.main_window)

# Create the widgets for the top frame.


self.name_label = tkinter.Label(self.frame1, text = 'Name ')
self.name_entry = tkinter.Entry(self.frame1, width = 20)

self.addr_label = tkinter.Label(self.frame2, text = 'address ')


self.addr_entry = tkinter.Entry(self.frame2, width = 20)

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 = tkinter.Label(self.frame4, text='Name ')


self.value1 = tkinter.StringVar()
self.name2_label = tkinter.Label(self.frame4,
textvariable = self.value1)
self.addr1_label = tkinter.Label(self.frame5, text='Address ')
self.value2 = tkinter.StringVar()
self.addr2_label = tkinter.Label(self.frame5,
textvariable = self.value2)

self.name1_label.pack(side='left')
self.name2_label.pack(side='left')
self.addr1_label.pack(side='left')
self.addr2_label.pack(side='left')

# Create the button


self.show_button = tkinter.Button(self.frame3, text = 'Display',
command = self.display)
self.quit_button = tkinter.Button(self.frame3, text = 'Quit',
command = self.main_window.destroy)
# Pack the buttons.
self.show_button.pack(side='left')
self.quit_button.pack(side='left')

Dept. of Mathematics–OU 29
Python Lab [CS205P] Date: |0 |2017

# Pack the frames.


self.frame1.pack()
self.frame2.pack()
self.frame3.pack()
self.frame4.pack()
self.frame5.pack()

# Enter the tkinter main loop.


tkinter.mainloop()

# Convert temperature from Celsius to Fahrenheit


def display(self):
self.value1.set(self.name_entry.get())
self.value2.set(self.addr_entry.get())

# Create an instance of the MyGUI class.


obj = Details()

Output:

Dept. of Mathematics–OU 30

You might also like