APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY
Sixth Semester [Link] Degree Examination June 2022 (2019 Scheme)
Course Code: CST362 Course Name: PROGRAMMING IN PYTHON
Max. Marks: 100 Duration: 3 Hours
Solution
PART A
Answer all questions, each carries 3 marks.
1 What is the output of the following print statement in Python? 3
(a) print (9//2) (b) print (9/2)
Answer: The ‘//’ operator in Python returns the integer part of the floating
number’/’ normal division
(a) 4 (b) 4.5
2 Write a Python program to count number of even numbers and odd 3
numbers in a given set of n numbers.
Answer:
def count_even_odd(numbers):
even_count = 0
odd_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count, odd_count
# Example usage
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even, odd = count_even_odd(numbers)
print("Number of even numbers:", even)
print("Number of odd numbers:", odd)
3 Illustrate the use of negative indexing of list with example. 3
Answer:
Use of negative indices is to refer to the end of the sequence:
index value of -1 gives the last element, and -2 gives the second last
element of
an array.
Example , b = “Hello, World!”
print(b[-5:-2]) output is orl
4 Write Python code for the following statements 3
i)writes the text” PROGRAMMING IN PYTHON” to a file with name
[Link]
ii) then reads the text again and prints it to the screen.
Answer:
of = open ( “code. txt” , “ w ” )
of. write (“PROGRAMMING IN PYTHON” )
fii= open ( “ code. txt ” , “ r ” )
text = fii . read ()
print text
5 List any three image processing Python libraries. 3
Answer:
images , SciPy, Scikit-Image Mahotas.,Pillow. OpenCV. SimpleITK
Matplotlib. NumPy.
6 List the steps to create a GUI application using Tkinter. 3
Answer:
Import the Tkinter module. import Tkinter
Create the GUI application main window. top = [Link]()
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by the
user. [Link]()
OR
Tkinter is the standard GUI library for Python. breezypythongui is sub
classing various classes in Python’s tkinter framework.
import breezypythongul , or import Easy Frame from breezypythongui,
Create the GUI application main window using __in it__() and add
components ,
creates an instance of the application window class and runs the main loop
method on this instance.
7 How to create a destructor in Python? Give an example. 3
Answer:
class MyClass:
def __init__(self, name):
[Link] = name
def __del__(self):
print(f"Destroying instance of {[Link]}")
# Example usage
obj1 = MyClass("Object 1")
obj2 = MyClass("Object 2")
del obj1
del obj2
8 Write a Python class which has two methods get_distance and 3
print_distance. get_distance accept a distance in kilometres from the user
and print_distance print the distance in meter.
Answer:
class DistanceConverter:
def __init__(self):
self.distance_km = 0
def get_distance(self):
self.distance_km = float(input("Enter the distance in kilometers: "))
def print_distance(self):
distance_meter = self.distance_km * 1000
print("Distance in meters:", distance_meter)
# Example usage
converter = DistanceConverter()
converter.get_distance()
converter.print_distance()
9 How do you assign a random number to a variable in Python? 3
Answer:
import random.
value = randint(1,10)
#1 and 10 represent the range for your random value.
print(value)
10 What is the use of os module in python? 3
Answer:
The OS module in Python provides functions for creating and removing a
directory (folder), fetching its contents, changing and identifying the
current directory, etc. import the os module to interact with the underlying
operating system
import os
# Get the current working directory (CWD)
cwd = [Link]()
PART B
Answer one full question from each module, each carries 14 marks.
Module I
11 a) Write a python program to generate the following type of pattern for the 6
given N rows.
1
12
123
1234
Answer:
n = int(input(“Enter the value of n : ”))
for i in range(1,n+1):
for j in range(1, i+1):
print(j,end=“ ”)
print()
b) Mention the different types of loop and control statements allowed in 8
Python and explain each type with suitable examples.
Answer:
Python provides several loop and control statements that allow you to
control the flow of execution in your programs. Here are the commonly
used loop and control statements in Python along with examples:
if statement: The if statement allows you to execute a block of code
conditionally based on a specific condition. It is used to make decisions in
your program. Here's an example:
x = 10
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
for loop: The for loop is used to iterate over a sequence (such as a list,
tuple, or string) or other iterable objects. It allows you to perform a set of
actions repeatedly for each item in the sequence. Here's an example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while loop: The while loop repeatedly executes a block of code as long as a
specific condition is true. It is used when you want to iterate until a
particular condition is met. Here's an example:
count = 0
while count < 5:
print("Count:", count)
count += 1
break statement: The break statement is used to exit a loop prematurely,
even if the loop condition is still true. It is often used when a specific
condition is met and you want to stop the loop. Here's an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
continue statement: The continue statement is used to skip the remaining
code inside a loop for the current iteration and move to the next iteration. It
is used when you want to skip some specific iteration but continue with the
next iteration. Here's an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
pass statement: The pass statement is a placeholder statement that does
nothing. It is used when you need a statement syntactically but don't want
to execute any code. Here's an example:
x=5
if x > 0:
pass # Placeholder for future code
else:
print("x is not positive")
These loop and control statements provide flexibility and control over the
execution flow in Python programs, enabling you to make decisions, iterate
over sequences, and control loop behavior based on specific conditions.
OR
12 a) Write the python program to print all prime numbers less than 1000. 7
Answer:
for i in range(1,1000):
prime = True
j=2
while (j <= i/2):
if (i % j == 0):
prime = False
break
j=j+1
if (prime):
print (i, end = ‘ ‘)
b Write a Python program to find distance between two points (x1,y1) and 7
(x2,y2).
Answer:
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
Square root sqrt() function can also be used instead of (**0.5)
Module II
13 a) Write a Python program to count how many times each character appears in 7
a given string and store the count in a dictionary with key as the character.
Answer:
strr = "Given string"
dict = {}
for i in strr:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
print ("Count of all characters :\n " + str(dict))
Output
Count of all characters :
{'G': 1, 'i': 2, 'v': 1, 'e': 1, 'n': 2, ' ': 1, 's': 1, 't': 1, 'r': 1, 'g': 1}
b) Create a function min_max() that takes n numbers as list argument and 7
return the smallest and largest numbers.
Answer:
def min_max(numbers):
if not numbers:
return None, None
smallest = largest = numbers[0]
for num in numbers:
if num < smallest:
smallest = num
if num > largest:
largest = num
return smallest, largest
# Example usage
numbers = [5, 2, 8, 1, 9, 3]
smallest, largest = min_max(numbers)
print("Smallest number:", smallest)
print("Largest number:", largest)
OR
14 Write a Python program to read n integers into a list and separate the positive 7
a) and negative numbers into two different lists.
Answer:
n = int(input("Enter how many numbers you want to enter: "))
arr=[]
positive=[]
negative=[]
for i in range(n):
number=int(input())
[Link](number)
for i in range(n):
if arr[i]>=0 :
[Link](arr[i])
else:
[Link](arr[i])
b Create a dictionary of names and birthdays. Write a Python program that asks 7
the user to enter a name, and the program display the birthday of that person.
Answer:
Birthdays={'A':'03/14/1879','B':'03/14/1879','C':'03/14/1879','D':'06/14/18669',}
print('Who's birthday do you want to look up?')
In_name = input()
print(Birthdays[In_name])
Module III
15 How to draw a star shape using turtle in Python. 5
a) Answer:
import turtle
ws = [Link]()
geekyTurtle = [Link]()
for i in range(5):
[Link](100)
[Link](144)
b) Explain basic image processing with inbuilt functions in Python. 7
Answer
Basic image processing can be performed in Python using various libraries,
such as PIL (Python Imaging Library) or its fork, Pillow, or the OpenCV
library. These libraries provide built-in functions and methods for performing
common image processing tasks. Here's an overview of some basic image
processing operations you can perform using these libraries:
Loading and Saving Images: You can use functions like open from PIL/Pillow
or imread and imwrite from OpenCV to load and save images in different
formats.
Resizing and Scaling: To resize an image, you can use the resize function from
PIL/Pillow or the resize function from OpenCV. These functions allow you to
specify the desired dimensions or scale factor to resize the image.
Cropping: To extract a specific region of interest from an image, you can use
the crop function from PIL/Pillow or the array slicing feature in OpenCV.
Filtering and Enhancing: You can apply various filters to an image, such as
blurring, sharpening, or edge detection. PIL/Pillow provides functions like
filter and enhance for applying filters. OpenCV offers functions like
GaussianBlur, filter2D, and Canny for similar operations.
Color Manipulation: You can convert an image to grayscale, adjust brightness,
contrast, or saturation levels, and perform color space conversions. PIL/Pillow
provides functions like convert, point, and split for these operations. OpenCV
offers functions like cvtColor, split, and merge for color manipulations.
Drawing on Images: You can draw various shapes, lines, text, or annotations
on an image. PIL/Pillow provides functions like [Link], [Link], and
[Link] for drawing on images. OpenCV offers functions like line, rectangle,
and putText for similar operations.
These are just a few examples of the basic image processing operations that can
be performed using built-in functions in Python libraries like PIL/Pillow and
OpenCV. Depending on the specific requirements, you can explore more
advanced operations like image segmentation, object detection, and feature
extraction, which often require more specialized algorithms and techniques.
OR
16 a) Write Python GUI program to take the birth date and output the age when a 7
button is pressed.
Answer:
from datetime import datetime
def calculate_age():
birth_date = [Link]() # Get the birth date from the entry widget
try:
# Convert the birth date string to a datetime object
birth_date = [Link](birth_date, "%Y-%m-%d")
current_date = [Link]() # Get the current date and time
# Calculate the age by subtracting the birth date from the current date
age = current_date.year - birth_date.year
# Display the age in a label widget
result_label.config(text=f"Your age is {age} years.")
except ValueError:
result_label.config(text="Invalid date format. Please enter a date in the
format YYYY-MM-DD.")
# Create the main window
window = [Link]()
[Link]("Age Calculator")
# Create a label widget for instructions
instructions_label = [Link](window, text="Enter your birth date (YYYY-
MM-DD):")
instructions_label.pack()
# Create an entry widget to input the birth date
entry = [Link](window)
[Link]()
# Create a button widget to calculate the age
button = [Link](window, text="Calculate Age",
command=calculate_age)
[Link]()
# Create a label widget to display the result
result_label = [Link](window, text="")
result_label.pack()
# Start the GUI event loop
[Link]()
b How do you display an image in Python GUI?. 7
Answer:
from tkinter import *
%from PIL import ImageTk,Image /// or using PIL
root = Tk()
canvas =Canvas(root, width = 300, height = 300)
[Link]()
img = PhotoImage(file="[Link]")
% img = [Link]([Link]("[Link]")) ////or using pil
canvas.create_image(20,20, anchor=NW, image=img)
mainloop()
OR
from breezypythongui import EasyFrame
from tkinter import PhotoImage
from [Link] import Font
Module IV
17 a) Demonstrate how polymorphism can be implemented using function 7
overloading with suitable example.
Answer:
class Shape:
def area(self):
pass
class Rectangle(Shape):
def area(self, length, width):
return length * width
class Circle(Shape):
def area(self, radius):
return 3.14 * radius * radius
# Create instances of the classes
rectangle = Rectangle()
circle = Circle()
# Call the area method with different arguments
rect_area = [Link](5, 3)
circle_area = [Link](2)
# Output the results
print("Area of rectangle:", rect_area)
print("Area of circle:", circle_area)
In the example above, we define a base class Shape with an area method
that is left empty. This method will be overridden in the derived classes.
The Rectangle and Circle classes inherit from the Shape class and
implement their own versions of the area method.
In Python, we can call different versions of the area method based on the
type of object we are working with. The Rectangle class has an area
method that takes two arguments, length and width, representing the
dimensions of the rectangle. The Circle class has an area method that takes
a single argument, radius, representing the radius of the circle.
By calling the area method on instances of the Rectangle and Circle
classes, we achieve polymorphism. The appropriate area method is called
based on the type of the object. The Rectangle object invokes its own area
method with two arguments, while the Circle object invokes its own area
method with one argument.
The output of the program will be:
Area of rectangle: 15
Area of circle: 12.56
As you can see, polymorphism allows objects of different classes to be
treated interchangeably based on their shared method names (area in this
case), even though the method implementations are different for each class.
b) Illustrate with a real life example how multi-level inheritance is 7
implemented in Python
Answer:
Multi-level inheritance occurs when a derived class inherits from another
derived class. In this type of inheritance, the derived class acts as the base
class for another derived class. This creates a hierarchical relationship
between the classes.
To illustrate multi-level inheritance, consider the following example:
class A:
def method_A(self):
print("This is method A")
class B(A):
def method_B(self):
print("This is method B")
class C(B):
def method_C(self):
print("This is method C")
# Create an object of class C
obj = C()
# Call methods from class A, B, and C
obj.method_A()
obj.method_B()
obj.method_C()
In this example, we have three classes: A, B, and C. Class A is the base
class, and class B is derived from class A. Class C is further derived from
class B, creating a multi-level inheritance structure.
The A class has a method called method_A, which simply prints a message.
The B class inherits from A and adds its own method called method_B.
Similarly, the C class inherits from B and adds its own method called
method_C.
By creating an object of class C, we can access and call methods from all
three classes. The object obj can invoke method_A from class A,
method_B from class B, and method_C from class C.
When we run the code, the output will be:
This is method A
This is method B
This is method C
# Python program to demonstrate
# multilevel inheritance
# Base class
class Grandfather:
def __init__(self, grandfathername):
[Link] = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
[Link] = fathername
# invoking constructor of Grandfather class
Grandfather.__init__(self, grandfathername)
# Derived class
class Son(Father):
def __init__(self,sonname, fathername, grandfathername):
[Link] = sonname
# invoking constructor of Father class
Father.__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', [Link])
print("Father name :", [Link])
print("Son name :", [Link])
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print([Link])
s1.print_name()
OR
18 a) Create an Abstract Base Class called Shape that include abstract methods 7
area() and circumference(). Then derive two classes Circle and Rectangle
from the Shape class and implement the area() and circumference()
methods . Write a Python program to implement above concept.
Answer:
from abc import ABC, abstractmethod
from math import pi
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def circumference(self):
pass
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return pi * [Link] * [Link]
def circumference(self):
return 2 * pi * [Link]
class Rectangle(Shape):
def __init__(self, length, width):
[Link] = length
[Link] = width
def area(self):
return [Link] * [Link]
def circumference(self):
return 2 * ([Link] + [Link])
# Create instances of the classes
circle = Circle(5)
rectangle = Rectangle(4, 6)
# Calculate and display the area and circumference of the circle
print("Circle:")
print("Area:", [Link]())
print("Circumference:", [Link]())
print()
# Calculate and display the area and circumference of the rectangle
print("Rectangle:")
print("Area:", [Link]())
print("Circumference:", [Link]())
In the example above, we import the ABC class from the abc module to
define the abstract base class Shape. The Shape class contains two abstract
methods, area() and circumference(). These methods are decorated with the
@abstractmethod decorator, indicating that any class deriving from Shape
must implement these methods.
The Circle class and Rectangle class both inherit from the Shape class and
provide their own implementations of the area() and circumference()
methods.
In the Circle class, the area() method calculates the area of the circle using
the formula pi * radius * radius, and the circumference() method calculates
the circumference using the formula 2 * pi * radius.
In the Rectangle class, the area() method calculates the area of the rectangle
by multiplying the length and width, and the circumference() method
calculates the circumference using the formula 2 * (length + width).
Finally, we create instances of the Circle and Rectangle classes and call the
area() and circumference() methods to calculate and display the area and
circumference of the respective shapes.
b How exceptions are handled in Python?. Illustrate with the help of an 7
example.
Answer:
In Python, exceptions can be handled using a try statement.
The critical operation which can raise an exception is placed inside the try
clause. The code that handles the exceptions is written in the except clause.
Example program
# Python Program to depict else clause with try-except
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Module V
19 a) Explain how the matrix multiplications are done using numpy arrays. 7
Answer:
import numpy as np
# Define the matrices
matrix1 = [Link]([[1, 2], [3, 4]])
matrix2 = [Link]([[5, 6], [7, 8]])
# Perform matrix multiplication
result = [Link](matrix1, matrix2)
# Print the result
print("Matrix Multiplication Result:")
print(result)
In this example, we import the NumPy library and create two matrices
using the [Link]() function. We then use the [Link]() function to
perform matrix multiplication between matrix1 and matrix2, storing the
result in the result variable. Finally, we print the result to the console.
b) How to plot two or more lines on a same plot with suitable legends, labels 7
and a title.
Answer:
import [Link] as plt
# Data for the lines
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
# Plot the lines
[Link](x, y1, label='Line 1')
[Link](x, y2, label='Line 2')
# Add labels and title
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Plot of Two Lines')
# Add legend
[Link]()
# Display the plot
[Link]()
In this example, we first import the [Link] module. We then
define the data points for the two lines: x represents the x-values, y1
represents the y-values for the first line, and y2 represents the y-values for
the second line.
We use the [Link]() function to plot the lines. Each [Link]() call plots a
line, and we provide the x and y values as arguments. We also use the label
parameter to assign a label to each line.
Next, we add labels to the x-axis and y-axis using [Link]() and
[Link](), respectively. We set the title of the plot using [Link](). To
include a legend for the lines, we use [Link]().
Finally, we use [Link]() to display the plot.
OR
20 a) Consider a CSV file ‘[Link]’ with the following columns(name, 8
gender, start_date ,salary, team).
Write commands to do the following using panda library.
1. print first 7 records from employees file
2. print all employee names in alphabetical order
3. find the name of the employee with highest salary
4. list the names of male employees
5. to which all teams employees belong
Answer:
import pandas as pd
df = pd.read_csv(‘[Link]")
1) [Link](7)
2) df= df.sort_values(‘name’,asvending=True)
print (df)
3) df=df[[‘name’,’salary’]][[Link]==df[‘salary’].max()]
4) df=df[[‘name’]][[Link]==’m’]
5) df=len([Link](df[‘team’]))
b Write Python program to write the data given below to a CSV file 7
Answer:
import pandas as pd
df = [Link]( insert values…………..
columns=['Reg_no ','Name','Sub_Mark1',' Sub_Mark2'',' Sub_Mark3'])
print("data frame =",df)