0% found this document useful (0 votes)
44 views6 pages

Python Programming Mock Exam Questions

The document is a mock exam for Python programming consisting of multiple-choice questions and essay questions. It covers various topics such as function creation, loops, string manipulation, and file handling. The exam includes a marking scheme for each question to evaluate the understanding and application of Python concepts.

Uploaded by

khongcl1307
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)
44 views6 pages

Python Programming Mock Exam Questions

The document is a mock exam for Python programming consisting of multiple-choice questions and essay questions. It covers various topics such as function creation, loops, string manipulation, and file handling. The exam includes a marking scheme for each question to evaluate the understanding and application of Python concepts.

Uploaded by

khongcl1307
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

Python Programming Mock Exam

Multiple Choice Questions (15 Questions, 1 Mark Each)

1. What is the correct syntax to create a function in Python?


o A) function myFunction():
o B) def myFunction:
o C) def myFunction():
o D) create myFunction():
2. Which of the following is used to start a loop in Python?
o A) for
o B) do
o C) while
o D) repeat
3. Which of the following is a valid method to add an element to a list?
o A) [Link]()
o B) [Link]()
o C) [Link]()
o D) [Link]()
4. How do you access the last element of a list myList in Python?
o A) myList[last]
o B) myList[-1]
o C) myList[0]
o D) myList[len(myList)]
5. What will the following code output? print(3 * '5')
o A) 15
o B) 555
o C) 5
o D) None
6. Which of the following is used for string interpolation in Python 3.6 and above?
o A) %
o B) str()
o C) f-strings
o D) format()
7. Which method is used to remove whitespace from the beginning and end of a string?
o A) strip()
o B) trim()
o C) remove()
o D) slice()
8. What does the break statement do in a loop?
o A) Ends the current loop iteration
o B) Exits the loop entirely
o C) Skips to the next iteration of the loop
o D) Pauses the loop
9. Which keyword is used to check if a key exists in a dictionary?
o A) in
o B) exists
o C) has_key
o D) contains
10. What is the output of len('Python')?
o A) 6
o B) 7
o C) 5
o D) None
11. What is the result of 2 ** 3 in Python?
o A) 8
o B) 6
o C) 9
o D) None
12. Which of the following statements is used to stop a loop prematurely?
o A) continue
o B) exit
o C) break
o D) return
13. How do you open a file for writing in Python?
o A) open(filename, 'r')
o B) open(filename, 'w')
o C) open(filename, 'a')
o D) open(filename, 'x')
14. Which of the following is a correct way to create a tuple?
o A) my_tuple = []
o B) my_tuple = {}
o C) my_tuple = ()
o D) my_tuple = <>
15. How would you handle an exception in Python?
o A) try-except
o B) catch-except
o C) try-catch
o D) catch-finally

Essay Questions (5 Questions, 5 Marks Each)

1. Using Functions to Process Data:


o Question: Write a Python function called process_data that takes a list of numbers as input
and returns the sum and average of the numbers. Provide the Python code and explain the
logic behind your implementation. Discuss the benefits of using functions for this task.
o Instructions
 Write a Python function that processes a list of numbers.
 Explain each step of your code, focusing on how the sum and average are
calculated.
 Discuss why using functions is beneficial in programming
o Marking Scheme:
 Correct function definition and parameter handling: 1 mark
 Correct calculation of sum and average: 2 marks
 Explanation of logic and return values: 1 mark
 Discussion of benefits of using functions: 1 mark
o Sample Solution:
o
o
2. Using Loops to Process Files:
o Question: Write a Python program that reads a text file line by line, counts the number of
words in each line, and then writes the result to a new file. Provide the Python code, and
explain how loops are utilized to process the file efficiently.
o Instructions:
 Develop a Python program to read a file and count words in each line.
 Write the results to another file.
 Explain how loops make this process efficient.
o Marking Scheme:
 Correct file handling (opening/closing files): 1 mark
 Accurate loop implementation for reading lines and counting words: 2 marks
 Explanation of how the loop works and processes the file: 1 mark
 Writing results to a new file: 1 mark
o Sample Solution:
o

3. Exploring String Interpolation:


o Question: Explain string interpolation in Python and its advantages over other string
formatting methods. Provide examples using f-strings and compare them with the format()
method.
o Instructions:
 Explain what string interpolation is in Python.
 Provide examples using both f-strings and the format() method.
 Discuss the advantages of using f-strings.
o Marking Scheme:
 Clear explanation of string interpolation: 1 mark
 Examples using f-strings: 2 marks
 Comparison with format() method: 1 mark
 Discussion of advantages: 1 mark
o Sample Solution:
o
4. Using Python Lists for Data Collection and Manipulation
o Question: Write a Python program that collects names of students in a class and stores them
in a list. The program should then allow the user to add new names, remove existing names,
and modify names in the list. Provide the Python code and explain how lists are used to
manage and manipulate this collection of data effectively.
o Instructions:
 Develop a Python program that demonstrates how to use lists for storing and
managing student names.
 Your program should include functions for adding, removing, and modifying names
in the list.
 Explain each function in detail and discuss the advantages of using lists for data
collection and manipulation.
 Provide code examples to illustrate your explanations.
o Marking Scheme:
 Correctly implementing list operations (add, remove, modify): 2 marks
1. 1 mark for correctly adding names to the list.
2. 0.5 marks for correctly removing names from the list.
3. 0.5 marks for correctly modifying names in the list.
 Explanation of how lists are used for data collection and manipulation: 2 marks
1. 1 mark for explaining how lists are used to store and organize data.
2. 1 mark for discussing the advantages of using lists, including flexibility and
ease of manipulation.
 Clear and correct Python code: 1 mark
1. 0.5 marks for code readability and correctness.
2. 0.5 marks for handling edge cases, such as attempting to modify or remove
a name that does not exist in the list.
o Sample Solution
o

5. Consider the following Python code snippet:

o Question: What will be the output of the code above, and why?

o Instructions:
 Read the Code Carefully: Examine the provided Python code snippet to understand
its behavior.
 Understand Variable Behavior: Pay attention to how variable assignment and list
mutability affect the output.
 Answer the Question: Determine the output of the code and explain why you
obtained that result.
o Marking Scheme:
 Correct Output (2 Marks):
1. The answer must correctly identify the output of the code:
1. 1 Mark: For correctly identifying the output of print(my_list).
2. 1 Mark: For correctly identifying the output of print(result).
2. Explanation of my_list Output (1 Mark):
1. 1 Mark: For correctly explaining that the original list my_list is
modified by [Link](4), but lst = [1, 2, 3] only affects the local
reference and does not change my_list.
3. Explanation of result Output (1 Mark):
1. 1 Mark: For correctly explaining that the returned value from the
function is [1, 2, 3], which is the new list created and assigned to
lst within the function.
4. Clarity and Completeness (1 Mark):
1. Mark: For providing a clear, logical, and complete explanation of
why the outputs are what they are, showing understanding of
variable scope and list mutability.
o Sample Solution:
 Expected Output:

 my_list Output:
o my_list is initially [0].
o The modify_list function appends 4 to lst, modifying the original
my_list to [0, 4].
o The assignment lst = [1, 2, 3] creates a new list and does not affect
my_list.
o After the function completes, my_list retains its modified value [0, 4].
 result Output:
o The function returns the new list [1, 2, 3] that was created within the
function.
o result captures this returned value.

Common questions

Powered by AI

Using functions for processing data in Python abstracts the logic into a reusable block of code that enhances modularity and readability. When calculating the sum and average of numbers in a list, functions encapsulate the operations, allowing you to focus on code logic without repeating calculations. This modularity facilitates testing and debugging as each function performs a specific task. Using functions also aids code organization, making it easier to maintain and extend by modifying the specific function without affecting other parts of the code .

The `break` statement immediately terminates the closest enclosing loop in Python, exiting the loop block prematurely. This is particularly useful in scenarios where a satisfactory condition is met early in the loop execution, allowing the program to skip unnecessary iterations that follow. For example, during a search in a large dataset, `break` can terminate the loop once the target is found, improving efficiency by avoiding additional checks .

Defining functions in Python leads to more organized and maintainable code by encapsulating repetitive tasks, thereby enhancing code readability and reducing redundancy. Functions allow developers to focus on modular pieces of logic, facilitating easier testing and debugging. In large projects, functions promote code reuse, simplify complex operations, and enable division of tasks among developers for collaborative development. This modular approach supports adaptability to changes, as separate functions can be modified or updated without affecting adjacent code, streamlining project maintenance and scaling .

Variable scope in Python dictates the accessibility of variables within different parts of the program. Variables defined within a function have a local scope, meaning they are not accessible outside that function and modifications to them do not affect variables with the same name outside the function. Conversely, variables defined outside functions can be accessed inside them but can only be modified if declared as global. This scope behavior facilitates encapsulation and prevents unintentional interference between function internals and global variables, ensuring data integrity .

String interpolation in Python involves embedding expressions within string literals using placeholders. F-strings, introduced in Python 3.6, allow for inline expression evaluation within string literals using curly braces. They are more readable and concise compared to the `format()` method as they resemble template literals and directly incorporate variables within the string. F-strings are also faster because they are processed as a single operation by Python's compiler, unlike `format()`, which needs to resolve all placeholders at runtime .

The output of `print(my_list)` is `[0, 4]` and the output of `print(result)` is `[1, 2, 3]`. This occurs because the statement `lst.append(4)` modifies the original list `my_list`, adding `4` to it. The later assignment `lst = [1, 2, 3]` creates a new list, referenced only by `lst` within the function, not affecting `my_list`. Therefore, the returned `result` is the new list `[1, 2, 3]`, while `my_list` retains its modified value of `[0, 4]` .

Lists in Python can dynamically store a collection of student names, allowing for easy addition, modification, and removal of names through methods like `.append()`, `.remove()`, and indexing. Lists are mutable, enabling direct modifications and are indexed, which supports quick access and updates to elements. The flexibility in data manipulation provided by lists is advantageous for organizing data, performing batch operations, and managing varying data sizes easily. Lists also support iterating over elements, making bulk operations straightforward .

Exception handling in Python is crucial for anticipating and resolving runtime errors, preventing program crashes, and maintaining functionality. A `try-except` block allows for the capturing of exceptions, executing alternative code if an error arises, and enables graceful error recovery. This enhances code robustness by allowing programs to continue execution after handling errors and providing meaningful error messages or alternative execution paths .

In Python, file modes determine how files are accessed. 'r' is for reading, positioning the cursor at file start; it throws an error if the file doesn't exist. 'w' is for writing, truncating the file to zero length if it exists, or creating it. 'a' appends data to the file end, preserving existing data. 'x' is for exclusive creation, failing if the file exists. These modes affect whether data is preserved, overwritten, or appended, impacting how updates are made to file contents .

Python loops process files efficiently as they allow for the systematic reading and processing of each line in a file, minimizing memory usage since only one line is loaded at a time. Loops enable operations such as reading, counting, and modifying data within a loop block, allowing for real-time data manipulation. This efficiency is further enhanced by using `with open()` which ensures proper file closure, and by leveraging `for` loops to iterate directly over file lines .

You might also like