0% found this document useful (0 votes)
88 views10 pages

M110 Final Spring 23 24 Key

The document is the answer key for the M110 Python Programming final examination for the Spring Semester 2023/2024. It includes multiple-choice questions, short answer questions, and programming problems, covering various Python concepts and functionalities. The exam consists of three parts with a total of 100 marks, and students are instructed to complete all questions in an external answer booklet.

Uploaded by

ÓMAŘ YQ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views10 pages

M110 Final Spring 23 24 Key

The document is the answer key for the M110 Python Programming final examination for the Spring Semester 2023/2024. It includes multiple-choice questions, short answer questions, and programming problems, covering various Python concepts and functionalities. The exam consists of three parts with a total of 100 marks, and students are instructed to complete all questions in an external answer booklet.

Uploaded by

ÓMAŘ YQ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

M110

Python Programming
Answer Key
Final Examination
Spring Semester 2023/2024

Date: ?? /May/2024

Number of Exam Pages: 9 Time Allowed: 3 Hours


(including this cover sheet)

Instructions:
 Total Marks:100
 This exam consists of 3 parts.
 ALL questions must be answered in the External Answer booklet.
 Be sure you write your name and ID on the External Answer booklet.
 Calculators are not allowed.

M110 / Final Page 1 of 10 2023/2024 Spring


PART 1: Multiple Choices questions [20 Marks]

1- Which of the following statements is correct?


a. In Python, you can use the read method to read a line from a file.
b. Anytime you assign a value to a variable inside a function, you create a
global variable.
c. Object-oriented programming is focused on creating functions.
d. Procedural programming is centered on creating functions.
2- Indefinite loops occur:
a. When you write a code inside the loop that makes the test condition false.
b. If the test condition is not changed.
c. If you forget to write code inside the loop that makes the test condition
false.
d. Both b and c.
3- In a class, behaviors are:

a. Properties c. Methods
b. Attributes d. Any of the choices.

4- In GUI, relief='flat' argument means that:

a. The border is hidden. c. The border has no 3D effect.


b. The border has 3D effect. d. Both a and c.
5- Which of the following List methods descriptions is correct?
a. insert(index, item) The item that was previously at the specified index will
be replaced with item.
b. count (item) returns the number of items in the list
c. pop(index) removes the item at the specified index and returns its value.
d. Both b and c.
6- In GUI, which of the below statements is not valid for the pack method:
a. determines where a widget should be positioned.
b. makes the widget visible when the main window is displayed.
c. Should be called for each widget in a window.
d. None of the choices.
7- If M= “Striking” and x=M[1:M.index("i")], then:

a. x= “trik” c. x=”tr”
b. x= “triking” d. Error

8- What is the output of the following code?

a. “vldtd” c. “dtdlv”
b. “tdlv” d. Error

9- When you use the 'a' mode to open an output file, then:

M110 / Final Page 2 of 10 2023/2024 Spring


a. If the file already exists, it c. If the file does not exist, it
will not be erased. will be created.
b. If the file does not exist, an d. Both a and c.
error occurs.

10-A/An______ is a software entity that contains data and procedures.

a. Variable. c. Object.
b. Method d. Class.

PART 2: Short Answer Questions [40 Marks]

Question 1: [6 marks]
Observe the following Python code very carefully and find the output.

i=0
x= [1, 2, 3, 4, 5, 3]
while i<len(x)-1:
x.remove(x[i])
i+=1
print("test")
print(x)

Answer: (6 marks: 1+1+1+3)


test
test
test
[2, 4, 3]

Question 2: [6 marks]
What is the output of the following code if the entered number of rows is 4?
rows = int(input("Enter number of rows: "))
number = 5
for i in range(1, rows+1):
for j in range(1, i+1):
print(number, end=" ")
number += 2
#print()
print()
print("Completed")

Answer: (6 marks: 1 mark for each line)

Enter number of rows: 4


5
79
M110 / Final Page 3 of 10 2023/2024 Spring
11 13 15
17 19 21 23
Completed

Question 3: [6 marks]
Observe the following Python code very carefully and find the output.

a=16
def challenge(a):
print("a is now:",a)
a=10
for ctr in range(1,a+1,1):
if (a/ctr - a//ctr)==0.0:
print(ctr, end=" ")
challenge(a)
print("\n",a, sep="")

Answer: (6 marks: 1+4+1)


a is now: 16
1 2 5 10
16

Question 4: [6 marks]
When creating a Label widget, you can use the borderwidth and relief arguments.
What does each one specify? Define briefly.

Answer: (6 marks: 3+3)


• The borderwidth argument specifies the width of the border, in pixels.

• The relief argument specifies the border style.

Question 5: [8 marks]
Given the problem specification below, you are asked to answer the corresponding
questions:
Problem specification: Prompt the user to enter a positive number n, then print the
count of all the odd numbers from 0 to n.
N.B: Assume that the entered number is a positive integer.
a- Write down the pseudocode of the above problem. (4 marks)
b- Write the Python code of the above problem. (4 marks)

Answer: (8 marks. 4+4. Tutors may award partial marks)

a- Pseudocode: 4 marks. One solution could be:


Step 1: count = 0,i=0
Step 2: Input n
M110 / Final Page 4 of 10 2023/2024 Spring
Step 3: While(i<=n)
if(i%2!=0)
count++
i++
Step 5: print count

b- Python code: 4 marks (The tutor can allocate marks based on the correctness of the
implemented code)
count=i=0
n=int(input("Enter a positive number: ")) # assuming integers are entered
while i<=n:
if i%2==1:
count+=1
i+=1
print(" You have", count, "odd numbers from",0,"to",n) # or just print(count)

or any equivalent code

Question 6: [8 marks]
Given a Python program that compares two lists, list1 and list2, to find and print
elements in list2 that are doubles of elements in list1. Additionally, the program
includes an operation to square each element in list1 and then append the squared
values to list1.
Here's the initial code with intentional four errors. Identify and correct the errors to
achieve the specified objective:

list1 = [3, 5, 7, 10, 8]


list2 = [6, 10, 14, 20, 16]
doubles_list = []
for i in range(len(list1))
for j in range(len(list2)):
if list2[j] = list1[i] * 2:
doubles_list.append(list2[i])
for i in range(len(list1)):
list1.append(list1[i] * 2)
print("Elements in list2 that are doubles of elements in list1:", doubles_list)
print("Squared values of elements in list1 added:", list1)

Answer: (8 marks)

list1 = [3, 5, 7, 10, 8]


list2 = [6, 10, 14, 20, 16]
doubles_list = []
for i in range(len(list1)):
for j in range(len(list2)):
if list2[j] == list1[i] * 2:
doubles_list.append(list2[j])
M110 / Final Page 5 of 10 2023/2024 Spring
for i in range(len(list1)):
list1.append(list1[i] ** 2)
print("Elements in list2 that are doubles of elements in list1:", doubles_list)
print("Squared values of elements in list1 added:", list1)

PART 3: Programming/Problem Solving Questions [40 Marks]


Question 1: [10 marks]
Write a function that takes a list of integers as an argument and returns the second
largest element in the list. The function should also return a proper message if the
length of the list is less than 2.
N.B: You can use any method/function.
Answer:
def find_second_largest(numbers):
if len(numbers) < 2:
return "List must contain at least two elements to
find the second-largest element."
else:
numbers.sort()
return numbers[-2]

Question 2: [10 marks]


Consider the incomplete Python program that should display the following window:

You are requested to write the following hidden commands, after carefully reading
the whole program , so that you properly use the variables:
1- Display the title.
2- Create two frames, one for the top of the window, and one for the bottom.
3- Pack the labels that are in the top frame.
4- Pack the frames.
5- Create the instance my_gui of the class.
N.B: Just write the code after indicating the part that you are answering.

from tkinter import *


class Grades:
def __init__(self):
# Create the main window widget.
self.root = Tk()
#Display a title.
self.root.title("Grades")
# Create two frames, one for the top, and one for the bottom.
self.top_frame = Frame(self.root)
self.bottom_frame = Frame(self.root)

M110 / Final Page 6 of 10 2023/2024 Spring


# Create three Label widgets for the top frame.
self.label1 = Label(self.top_frame,text='Math')
self.label2 = Label(self.top_frame,text='Python')
self.label3 = Label(self.top_frame,text='English')
# Pack the labels that are in the top frame.
self.label1.pack(side='top')
self.label2.pack(side='top')
self.label3.pack(side='top')
# Create three Label widgets for the bottom frame.
self.label4 = Label(self.bottom_frame,text='Math Average')
self.label5 = Label(self.bottom_frame,text='Python Average')
self.label6 = Label(self.bottom_frame,text='English Average')
# Pack the labels that are in the bottom frame.
self.label4.pack(side='left')
self.label5.pack(side='left')
self.label6.pack(side='left')
#Pack the frames
self.top_frame.pack()
self.bottom_frame.pack()
# Enter the tkinter main loop.
mainloop()
# Create an instance of the class.
my_gui = Grades()

Answer: (10 marks: 2 marks for each part)

1- (2 marks)
self.root.title("Grades")
2- (2 marks)
self.top_frame = Frame(self.root)
self.bottom_frame = Frame(self.root)
3- (2 marks: the answer is accepted if the student did not include side {default is top})
self.label1.pack(side='top')
self.label2.pack(side='top')
self.label3.pack(side='top')
4- (2 marks)
self.top_frame.pack()
self.bottom_frame.pack()
5- (2 marks)
my_gui = Grades()

Question 3: [10 marks]


Answer the following questions:
a. Write a Python code that creates the below file.

M110 / Final Page 7 of 10 2023/2024 Spring


b. Write a Python code that reads the above file lines into a list and produces the
following output.
List of Lines from the File:
['Nader Ballout', 'Abir Ahmad', 'Nadia Abdullah', 'Fadi Salem']

Answer: (10 marks: 5+5)


a. (5 marks)

myfile = open('Std_Name.txt', 'w') # 1.5 marks


# Write my data to the file. # 3 marks
#Students can use also 4 write statements instead of using a loop
num=int(input("Enter the number of lines you want to enter: "))
for i in range(num):
line=input("Enter the line: ")
myfile.write(line+'\n')
# Close the file.
myfile.close() # 0.5 mark

b. (5 marks)

Solution #1:
# Open the file in read mode
myfile = open('Std_Name.txt', 'r') # 1.5 marks
# Initialize an empty list to store lines
lines_list = []
# Read the lines # 2.5 marks
line = myfile.readline()
while line:
# Append the line to the list
lines_list.append(line.rstrip('\n'))
# Read the next line
line = myfile.readline()
# Close the file
myfile.close()
# Print the list of lines # 1 mark
print("List of Lines from the File:")
print(lines_list)

Solution #2:
# Open the file in read mode
myfile = open('Std_Name.txt', 'r') #1.5 marks
M110 / Final Page 8 of 10 2023/2024 Spring
# Initialize an empty list to store lines
lines_list = []
# Read the lines # 2.5 marks
for i in range(4):
line = myfile.readline()
# Append the line to the list
lines_list.append(line.rstrip("\n"))
# Close the file
myfile.close()
# Print the list of lines # 1 mark
print("List of Lines from the File:")
print(lines_list)

Solution #3:
f=open('Std_Name.txt',"r") # 1.5 marks
content_list = f.readlines() # 1.5 marks
# remove new line characters # 1 mark
for i in range(len(content_list)):
content_list[i]= content_list[i].strip()
# Print the list of lines # 1 mark
print("List of Lines from the File:")
print(content_list)

Question 4: [10 marks]


Develop a Python program that:
1. Defines a class called Rectangle with an initializer that takes the
length and width as parameters.
2. Includes a Perimeter() method to calculate the perimeter of the rectangle.
3. Includes an Area() method to calculate the area of the rectangle.
4. Includes a method display() that displays the length, width, perimeter and
area.
5. Instantiate the class with the expected values (say 7 and 5) and write the
necessary statement(s) to display length, width, perimeter and area of the
rectangle.
N.B: The perimeter of the rectangle=2(length + width), and the area=
length*width.

Answer: (10 marks: 2 marks for each part)


class Rectangle:
# define constructor with attributes: length and width 2
marks
def __init__(self, length , width):
self.length = length
self.width = width

# Create Perimeter method 2 marks


def Perimeter(self):
return 2*(self.length + self.width)

M110 / Final Page 9 of 10 2023/2024 Spring


# Create area method 2 marks
def Area(self):
return self.length*self.width
# create display method 2 marks
def display(self):
print("The length of rectangle is: ", self.length)
print("The width of rectangle is: ", self.width)
print("The perimeter of rectangle is: ",
self.Perimeter())
print("The area of rectangle is: ", self.Area())

# Instantiation and display 2 marks


myRectangle = Rectangle(7 , 5)
myRectangle.display()

End of questions

M110 / Final Page 10 of 10 2023/2024 Spring

You might also like