Cohort 24
Cohort 24
Your Task
The test score is over 15. You would get a 30 marks deduction if you have
similar answers with anyone, even for one question. So if you decide to use an
LLM (ChatGPT etc….) , remember there is someone that would probably do the
same, example me :)
TAKE NOTES
● Provide brief comments in your code explaining the logic where necessary.
● Ensure your inputs and outputs are clear and consistent with the problem statement.
● Ensure your code runs without syntax errors or crashes (when valid inputs are
provided).
● If a code isn’t warranted for a question, answer in a comment line. Be expressive and
Creative
QUESTIONS
2. You wrote a script that opens a file, reads the contents, and closes it. However,
after running the script, you check the file, and the contents seem unchanged.
What might have gone wrong?
3. You are given a large log file (log.txt) that contains thousands of lines. Without
reading the entire file into memory at once, how would you extract only the last 50
:
lines?
4. You are writing to a file using "w" mode and "a" mode. You notice that in both
cases, the file content grows over time. Explain why this might happen for
"w" mode when it is supposed to overwrite.
try:
Without modifying the except blocks, how can you make this code fail to catch an error
when a user enters "0.0"?
8. You create a function that handles multiple exceptions using a single except
Exception: block. Later, you notice that catching all exceptions this way
sometimes causes unexpected issues. Explain why this might be a bad practice.
9. You define a function inside another function, and the inner function tries to
modify a variable from the outer function without using global or nonlocal.
However, the code runs without errors. How is this possible? After explaining
include a code to illustrate
def mystery(a=[]):
a.append(42)
return a
10. Explain why calling mystery() multiple times returns different results.
:
11. Write a function safe_write(filename, data) that writes data to a file.
Ensure that if the function crashes midway, the file remains uncorrupted.
12. You need to rename all .txt files in a folder by adding a _backup suffix before
the extension (e.g., notes.txt → notes_backup.txt). Write a Python script to
do this.
13. You have two large files, file1.txt and file2.txt, and need to efficiently
merge their contents into merged.txt without loading both files into memory at
once. Implement this.
14. A function that reads a user’s age from input throws an error when the user
enters non-numeric characters. Modify it to handle all edge cases properly.
15. Write a function that accepts any number of arguments and returns the sum of
only the even numbers.
: