Uploaded by Sameh Gamal

Python Programming Exam Solution - Fall 2023/2024

advertisement
M110
Python Programming
Final Examination
Solution
Fall Semester 2023/2024
Date: ?? /??/2024
Number of Exam Pages: 8
(including this cover sheet)
Time Allowed: 3 Hours
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 Exam
Page 1 of 8
Fall 2023/2024
PART 1: Multiple Choices questions [20 Marks]
This part consists of 10 questions carrying a WEIGHT OF 2 marks for each. Answer the questions by
choosing the most correct choice.
1- Which of the following is not correct?
a. If the condition is true, the while statement will execute its block of statements.
b. The “while” clause is composed of the while word, the condition, and the semi colon.
c. The “for” block should be indented.
d. None of the above.
2- Which of the following statements is not correct?
a. In Python, Lists are written as comma-separated items within squared brackets.
b. In Python, Tuple is a collection of data, items are enclosed within curly brackets.
c. In Python, Tuples are immutable.
d. None of the choices.
3- 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(x) removes the item x and returns its value.
d. None of the choices.
4- To open and read text file that is named StudentRec.txt that exists in folder D:\python.
Which of the following statements is the easiest way to read this file, given that the Python
program is located under the same folder:
a. file = open('StudentRec.txt', 'r')
b. file = open('D:\\python\\StudentRec.txt', 'r')
c. file = open('StudentInfo.txt')
d. file = open('D:\python\StudentRec.txt', 'r')
5- A graphical element that the user can interact with, or view is called:
a. GUI
c. Widget
b. CLI
d. Control unit.
6- What is the purpose of the return statement in a function?
a. To exit the function
c. To transfer control to the calling
b. To return a value to the calling
function
function
d. To end the function execution
7- What is the output of the following code?
x = [1, 2, 3]
y=x
y[0] = 4
print(x)
a. [1, 2, 3]
b. [4, 2, 3]
c. 1 2 3
d. Error
8- 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. Determines the border width and relief.
M110 – Final Exam
Page 2 of 8
Fall 2023/2024
9- In tkinter, the widget Frame is:
a. An area that displays one line of text or an image.
b. An area in which the user may type a single line of input.
c. An area that displays multiple lines of text.
d. A container that can hold other widgets.
10- What is the output of the following code?
x = [1, 2, 3]
for i in range(len(x)):
x.remove(x[i])
print(x)
c. [1, 2]
a. []
d. Error message.
b. [2, 3]
PART 2: Short Answer Questions [40 Marks]
This part consists of 6 questions. You should attempt all questions.
You should dedicate approximately 75 minutes to this part.
Question 1: [6 marks]
Find the value of x and y after executing the following code:
x = 10
y = 15
if x>10 and y <20:
x+=1
y-=1
else:
x-=2
y*=2
print("The value of x will be:",x)
print("The value of y will be:",y)
Solution: (6 marks: 3 marks for each correct line)
The value of x will be: 8
The value of y will be: 30
Question 2: [6 marks]
What will be displayed on the screen if the following program is executed, if all entered values are
non-negative, and the set of numbers that the user intends to enter is: 11,12, 6, 0, 3, 5, 0,12,10?
odd_count = 0
even_count = 0
num = int(input("Enter a positive integer (0 to stop): "))
while num!=0:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
num = int(input("Enter a positive integer (0 to stop): "))
print("Odd numbers entered:", odd_count)
print("Even numbers entered:",even_count)
Solution: (6 marks: 0.5 marks for each of the first 4 lines; 2 marks for each of the last 2 lines)
M110 – Final Exam
Page 3 of 8
Fall 2023/2024
Enter a positive integer (0 to stop): 11
Enter a positive integer (0 to stop): 12
Enter a positive integer (0 to stop): 6
Enter a positive integer (0 to stop): 0
Odd numbers entered: 1
Even numbers entered: 2
Question 3: [6 marks]
Write a Python function to find the largest word in a list and return it.
Solution: (6 marks. Partial marks can be awarded)
def find_largest_word(word_list):
largest_word = word_list[0]
for word in word_list:
if len(word) > len(largest_word):
largest_word = word
return largest_word
Question 4: [6 marks]
Given the following python code.
a- What does this code do?
b- What is the output of the above code?
Answer: (6 marks: 3 marks for each part)
a- This function computes the factorial of the argument passed.
b- Output: The result of the function for 5 is: 120
Question 5: [8 marks]
List four restrictions on the Python variable name.
Answer: Some valid restrictions (8 marks: 2 marks for each)
• Variable names cannot contain the dollar sign.
• Variable names cannot contain spaces.
• Variable names cannot start with a number.
• Variable names cannot be one of the reserved words.
M110 – Final Exam
Page 4 of 8
Fall 2023/2024
Question 6: [8 marks]
What is the output of the following code?
list1 = [12, 5, 6, 7, 2, 9, 5, 6]
i=0
while i< len(list1):
item = list1[i]
if list1.count(item) > 1:
list1.remove(item)
else:
i+= 1
print(list1)
Answer:
[12, 7, 2, 9, 5, 6]
PART 3: Programming/Problem Solving Questions [40 Marks]
This part consists of 4 questions. You must attempt all questions.
You should dedicate approximately 90 minutes to this part.
Question 1: [10 marks]
Write a Python program to check if a triangle is equilateral, isosceles, or scalene.
Note:
An equilateral triangle is a triangle in which all three sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal sides.
Expected Output:
Input lengths of the triangle sides:
x: 6
y: 8
z: 12
Scalene triangle
Answer:
print("Input lengths of the triangle sides: ")
x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))
if x == y == z:
print("Equilateral triangle")
elif x==y or y==z or z==x:
print("isosceles triangle")
else:
print("Scalene triangle")
M110 – Final Exam
Page 5 of 8
Fall 2023/2024
Question 2: [10 marks]
a- Write a Python function fill_List that prompts the user to enter positive integers.
The function should keep on entering the integers and adding them to a list until a
negative number is entered. Make sure that this list can be used in other parts of a
program. (7 marks)
b- Suppose that we want to call the above function and print only the numbers that are
multiples of 3 on one line. Write down the statements that implement the task. (3 marks)
Expected Output:
Enter a positive integer (negative to exit): 0
Enter a positive integer (negative to exit): 2
Enter a positive integer (negative to exit): 3
Enter a positive integer (negative to exit): 5
Enter a positive integer (negative to exit): 6
Enter a positive integer (negative to exit): 9
Enter a positive integer (negative to exit): -1
Numbers that are multiples of 3:
0 3 6 9
Answer: (10 marks: 7+3. Tutors may award partial marks)
a- def fill_List():
# a. Function to fill the list with positive integers until a negative number is entered
def fill_List():
number_list = [] # Initialize an empty list to store the numbers
while True:
num = int(input("Enter a positive integer (negative to exit): "))
if num < 0:
break
number_list.append(num)
return number_list
# b. Calling the function and printing multiples of 3
numbers = fill_List()
print("Numbers that are multiples of 3:")
for num in numbers:
if num % 3 == 0:
print(num, end=" ") # Print multiples of 3 on one line
or any equivalent code
Question 3: [10 marks]
Given an incomplete code of a program that should produce the below figure, you are asked to
replace the bold letters with the proper piece of code. N.B: read the whole code before answering,
as some of the missing parts are already shown in the available code lines and comments.
from tkinter import *
A
def __init__(self):
B = Tk()
self.root.title('M110 Fall 23-24')
#Create two widgets with solid borders with width=2
C
D
#Display the labels with 15 pixels of horizontal and vertical padding for each.
# The labels should be far from each other horizontally by 10 pixels
self.label1.pack(side="left", ipadx=15, ipady=15)
E
mainloop()
my_gui = GUI_2023 ()
M110 – Final Exam
Page 6 of 8
Fall 2023/2024
Answer: (10 marks: deduct 2 marks for any other incorrect answer)
from tkinter import *
class GUI_2023:
def __init__(self):
self.root = Tk()
self.root.title('M110 Fall 23-24')
#create two widgets with solid borders with width=2
self.label1 =Label(self.root,text='Final Exam!',borderwidth=2,relief='solid')
self.label2 = Label(self.root, text='Good Luck!',borderwidth=2,relief='solid')
#display the labels far from each other by 10 pixels
self.label1.pack(side="left", ipadx=15, ipady=15)
self.label2.pack(side="left", ipadx=15, ipady=15, padx=10)
mainloop()
my_gui = GUI_2023 ()
Question 4: [10 marks]
You are requested to write a python program that does the following:
a. Create a Python program that defines a class called NumberProcessor with an initializer
that takes a positive number as a parameter. (Assume that the entered number is positive)
b. Implement a method called find_even_odd() within the class. This method should determine
and return whether the number is even or odd.
c. Implement another method called reverse_number() within the class. This method should
reverse the digits of the positive number and return the reversed number.
d. Instantiate the class after prompting the user to enter a positive number and write the
necessary statements to test both find_even_odd() and reverse_number().
Expected Output:
Enter a positive number: 12345
The number is Odd.
The reversed number is 54321.
Answer: (10 marks: 3 marks for each of parts a and d, 2 marks for each of parts b and c)
class NumberProcessor:
def __init__(self, number):
# Initialize the class with a positive integer 'number'
self.number = number
def find_even_odd(self):
# Method 1: Determine if the number is even or odd
if self.number % 2 == 0:
return "Even"
else:
return "Odd"
M110 – Final Exam
Page 7 of 8
Fall 2023/2024
def reverse_number(self):
# Method 2: Reverse the digits of the number
reversed_num = ""
num = str(self.number)
for i in range(len(num)-1, -1,-1):
reversed_num += num[i]
return reversed_num
# Get user input for a positive integer
number = int(input("Enter a positive number: "))
# Instantiate the class
processor = NumberProcessor(number)
# Test both methods
result_even_odd = processor.find_even_odd()
result_reverse = processor.reverse_number()
# Display the results
print(f"The number is {result_even_odd}.")
print(f"The reversed number is {result_reverse}.")
or any equivalent code
__________________________________________________________________________
End of Questions
M110 – Final Exam
Page 8 of 8
Fall 2023/2024
Download