Unit 6: Files and Exceptions; Regular Expressions - Practice Quiz
1 What is a text file mainly used to store?
2 Which method converts a value into a string before writing it to a text file?
open()
str()
list()
int()
3 Which method reads the entire contents of an open file?
remove()
write()
read()
close()
4 Which file mode is commonly used to write data to a file and replace its existing contents?
r
w
a
x
5 Which method writes a string to an open file?
seek()
write()
split()
read()
6 Which Python module provides functions for working with directories?
random
os
math
string
7 Which function creates a new directory in Python?
os.read()
os.open()
os.file()
os.mkdir()
8 What is pickling in Python?
9 Which Python module is commonly used for pickling objects?
calendar
pickle
statistics
pprint
10 What exception is raised when a number is divided by zero in Python?
ZeroDivisionError
NameError
ValueError
TypeError
11 Which statement can prevent a program from stopping when division by zero occurs?
print statement
try-except block
return statement
continue statement
12
What code is placed inside the try block?
13
What is the purpose of an except block?
14
When does the else block of a try-except statement run?
try block starts
15
When is FileNotFoundError commonly raised?
16 Which exception should be caught when opening a file that may not exist?
IndexError
ZeroDivisionError
FileNotFoundError
KeyError
17 What is a regular expression?
18
In a regular expression, what does \d usually represent?
19
What does re.match() check by default?
20 How can regular expressions help with web scraping?
21
A text file contains red\nblue\n. What is the value of data after the following code runs?
with open("colors.txt", "r") as file:
data = file.read().splitlines()
("red", "blue")
"red blue"
["red", "blue"]
["red\n", "blue\n"]
22
The variable score contains the integer 95. Which statement correctly writes Score: 95 to an already opened text file named file?
file.write("Score: " + str(score))
file.write("Score: " + score)
file.write(["Score: ", score])
file.write("Score: ", str(score))
23
A file contains three lines: A, B, and C. What does the following code print?
with open("letters.txt", "r") as file:
first = file.readline()
remaining = file.readlines()
print(len(remaining))
1
0
3
2
24
A file named log.txt already contains Start\n. Which mode should be used to add End\n without deleting the existing content?
open("log.txt", "a")
open("log.txt", "x")
open("log.txt", "w")
open("log.txt", "r")
25
Which expression creates a platform-independent path to report.txt inside the data directory?
os.path.concat("data", "report.txt")
os.path.join("data", "report.txt")
os.join.path("data", "report.txt")
os.path.make("data", "report.txt")
26
Which statement creates the nested directories results/2025/june even if the parent directories do not yet exist?
os.listdir("results/2025/june")
os.makedirs("results/2025/june")
os.chdir("results/2025/june")
os.mkdir("results/2025/june")
27
Two objects are stored as follows:
with open("data.pkl", "wb") as file:
pickle.dump([1, 2], file)
pickle.dump({"x": 3}, file)
How should both objects be restored?
pickle.load(file) twice in the same order
file.read() twice and convert each result
pickle.loads(file) twice in reverse order
pickle.load(file) once to obtain both objects
28
Which file-opening statement is appropriate when restoring a pickled object from model.pkl?
open("model.pkl", "wb")
open("model.pkl", "rb")
open("model.pkl", "r")
open("model.pkl", "a")
29
What does this code print when the user enters 0?
try:
value = 20 / int(input())
except ZeroDivisionError:
print("Cannot divide")
else:
print(value)
Cannot divide
0
ValueError
20
30
Which exception is raised and handled when this code receives the input three?
try:
count = int(input())
result = 12 / count
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Zero is not allowed")
ValueError, printing Invalid number
TypeError, printing no message
ZeroDivisionError, printing Zero is not allowed
NameError, printing no message
31
When does the else block associated with a Python try-except statement execute?
try block finishes without an exception
try block raises every listed exception
finally block is omitted from the statement
except block finishes handling an exception
32
Which structure handles a missing settings.txt file while allowing other input/output errors to propagate?
try: open("settings.txt") followed by except FileNotFoundError:
try: open("settings.txt") followed by except IOError:
try: open("settings.txt") followed by except RuntimeError:
try: open("settings.txt") followed by except Exception:
33
Why is the raw string r"\d+" commonly used for a regular expression that matches digits?
34 Which pattern matches a product code containing exactly two uppercase letters followed by exactly three digits?
r"^[A-Z]{2}\d{3}$"
r"^[A-Z]{3}\d{2}$"
r"^[a-z]{2}\d{3}$"
r"^[A-Z]+\d+$"
35
Which regular expression matches either color or colour, but not colouur?
r"colou+r"
r"colou*r"
r"colou?r"
r"colo.r"
36
What is the result of re.match(r"\d+", "ID: 123")?
ID
123
None
ID: 123
37
What does result.group(2) return after this code runs?
result = re.match(r"([A-Za-z]+)-(\d+)", "Item-204")
"204"
"Item-204"
"-204"
"Item"
38
Given html = '<a href="/home">Home</a><a href="/help">Help</a>', which expression extracts both URL values?
re.match(r'href="([^"]+)"', html)
re.split(r'href="([^"]+)"', html)
re.findall(r'href="([^"]+)"', html)
re.sub(r'href="([^"]+)"', html)
39
An HTML fragment contains <p>First</p><p>Second</p>. Which pattern used with re.findall() captures First and Second separately?
r"<p>*</p>"
r"<p>(.*)</p>"
r"<p>(.*?)</p>"
r"<p>.+</p>"
40
A page source contains <title>Python\nGuide</title>. Which call captures the title text even though it spans two lines?
re.findall(r"^<title>(.*?)</title>$", html)
re.match(r"<title>(.*?)</title>", html, re.MULTILINE)
re.search(r"<title>(.*?)</title>", html, re.DOTALL)
re.search(r"<title>(.*?)</title>", html, re.ASCII)
41
A file is opened with open("data.txt", "w"), text is written, and the program terminates without explicitly calling close(). Which statement is most accurate?
42
Consider x = 7, y = 2.5, and f.write(x). What happens, and what is the correct way to write the value as text?
7 because integers are automatically converted
ValueError; use f.write(int(x))
TypeError; use f.write(str(x))
43
A file contains alpha\nbeta\n. After lines = f.readlines(), which result is produced when the file is opened in normal text mode?
["alpha", "beta"]
["alpha", "beta", ""]
"alpha\nbeta\n"
["alpha\n", "beta\n"]
44
Suppose log.txt already contains A\nB\n. The code with open("log.txt", "w") as f: f.write("C\n") is executed. What is the final content?
FileExistsError
A\nB\nC\n
C\nA\nB\n
C\n
45
Which statement best explains why os.mkdir("reports/2025/january") can fail even when the current directory exists?
os.mkdir() works only with absolute paths
os.mkdir() creates only one directory level
46
Why is loading an untrusted file with pickle.load() considered unsafe?
47 A program pickles an object containing a class instance, then the class definition is renamed before unpickling. What is the most likely result?
48
What does the following code print? try: print(10 / 0)\nexcept ZeroDivisionError: print("invalid")\nprint("done")
done followed by invalid
invalid followed by done
invalid
49
What is the main problem with writing except Exception: around an entire file-processing program without logging or re-raising the exception?
50
For the code try: value = int("3.5")\nexcept ValueError: value = 0, what is the final value of value?
0 because integer conversion rejects decimal text
3.5 as a floating-point value
3 as an integer
51
In a try-except-else construct, when does the else block execute?
try block completes without an exception
try block begins
finally block regardless of failure
52
Why is f.write(result) often placed in the else block after successfully opening and reading a file?
else block execute before the try block
53
A program uses open("input.txt", "r") inside a try block and catches FileNotFoundError. Which situation can still cause a different exception?
54 Which design best avoids accidentally destroying a file when a program intends to update it only after successfully reading its contents?
"r+" and assume failed reads leave all content unchanged
"w" mode for replacement
"a" mode and overwrite from the beginning
"w" mode before attempting the read
55
What does the regular expression ^\d{4}-\d{2}-\d{2}$ assert when applied with a full-string match?
56 Which pattern correctly matches a Python identifier that begins with a letter or underscore and continues with letters, digits, or underscores?
^[_A-Za-z]\d*$
^[A-Za-z_]\w*$
^[A-Za-z0-9]+$
^\w+[A-Za-z_]$
57
What is the practical difference between the patterns a+ and a* when matching a string?
a
a* matches only the literal character *
a+ permits zero or one a, while a* requires one
a+ requires at least one a, while a* permits zero or more
58
Given pattern = re.compile(r"cat"), which statement correctly distinguishes pattern.match("concatenate") from pattern.search("concatenate")?
match succeeds at the beginning; search finds cat later
match finds all occurrences; search finds only the first character
match ignores order; search requires the pattern at index zero
cat is not the whole string
59
What does m = re.match(r"(?P<area>\d{3})-(\d{4})", "212-5555") make available if m is not None?
m.group("area") is the complete string only
m.group("area") is "212" and m.group(2) is "5555"
m.group("area") is "5555" and m.group(2) is "212"
60
Why is using a regular expression such as <a href="(.*?)">(.*?)</a> generally unreliable for extracting links from arbitrary HTML?
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →