Unit 6: Files and Exceptions; Regular Expressions - Practice Quiz

INT108 — Python Programming 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is a text file mainly used to store?

Text files Easy
A. Only image data
B. Human-readable characters
C. Computer hardware settings
D. Only executable programs

2 Which method converts a value into a string before writing it to a text file?

Writing variables Easy
A. open()
B. str()
C. list()
D. int()

3 Which method reads the entire contents of an open file?

Reading from a file Easy
A. remove()
B. write()
C. read()
D. close()

4 Which file mode is commonly used to write data to a file and replace its existing contents?

Writing to a file Easy
A. r
B. w
C. a
D. x

5 Which method writes a string to an open file?

Writing to a file Easy
A. seek()
B. write()
C. split()
D. read()

6 Which Python module provides functions for working with directories?

Directories Easy
A. random
B. os
C. math
D. string

7 Which function creates a new directory in Python?

Directories Easy
A. os.read()
B. os.open()
C. os.file()
D. os.mkdir()

8 What is pickling in Python?

Pickling Easy
A. Sorting values alphabetically
B. Converting numbers into fractions
C. Converting objects into a byte stream
D. Removing files from a directory

9 Which Python module is commonly used for pickling objects?

Pickling Easy
A. calendar
B. pickle
C. statistics
D. pprint

10 What exception is raised when a number is divided by zero in Python?

Handling the ZeroDivisionError exception Easy
A. ZeroDivisionError
B. NameError
C. ValueError
D. TypeError

11 Which statement can prevent a program from stopping when division by zero occurs?

Handling the ZeroDivisionError exception Easy
A. A print statement
B. A try-except block
C. A return statement
D. A continue statement

12 What code is placed inside the try block?

Using try-except blocks Easy
A. Only comments about the program
B. Only code that runs after success
C. Code that may raise an exception
D. Only code that closes the program

13 What is the purpose of an except block?

Using try-except blocks Easy
A. To open a directory
B. To define a new variable
C. To repeat a loop
D. To handle an exception

14 When does the else block of a try-except statement run?

The else block Easy
A. Only when the file is missing
B. When no exception occurs
C. Before the try block starts
D. When every exception occurs

15 When is FileNotFoundError commonly raised?

Handling the FileNotFoundError exception Easy
A. When a number is divided by zero
B. When a requested file is missing
C. When a string is printed
D. When a list is sorted

16 Which exception should be caught when opening a file that may not exist?

Handling the FileNotFoundError exception Easy
A. IndexError
B. ZeroDivisionError
C. FileNotFoundError
D. KeyError

17 What is a regular expression?

Concept of regular expressions Easy
A. A pattern for matching text
B. A format for saving images
C. A tool for creating folders
D. A method for adding numbers

18 In a regular expression, what does \d usually represent?

Various types of regular expressions Easy
A. A newline
B. A letter
C. A digit
D. A space

19 What does re.match() check by default?

Using the match function Easy
A. Only numeric results
B. The end of a string
C. Every file in a folder
D. The beginning of a string

20 How can regular expressions help with web scraping?

Web scraping using regular expressions Easy
A. By designing computer hardware
B. By finding matching text patterns
C. By encrypting every web page
D. By increasing internet speed

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()

Text files Medium
A. ("red", "blue")
B. "red blue"
C. ["red", "blue"]
D. ["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?

Writing variables Medium
A. file.write("Score: " + str(score))
B. file.write("Score: " + score)
C. file.write(["Score: ", score])
D. 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))

Reading from a file Medium
A. 1
B. 0
C. 3
D. 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?

Writing to a file Medium
A. open("log.txt", "a")
B. open("log.txt", "x")
C. open("log.txt", "w")
D. open("log.txt", "r")

25 Which expression creates a platform-independent path to report.txt inside the data directory?

Directories Medium
A. os.path.concat("data", "report.txt")
B. os.path.join("data", "report.txt")
C. os.join.path("data", "report.txt")
D. 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?

Directories Medium
A. os.listdir("results/2025/june")
B. os.makedirs("results/2025/june")
C. os.chdir("results/2025/june")
D. 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?

Pickling Medium
A. Call pickle.load(file) twice in the same order
B. Call file.read() twice and convert each result
C. Call pickle.loads(file) twice in reverse order
D. Call pickle.load(file) once to obtain both objects

28 Which file-opening statement is appropriate when restoring a pickled object from model.pkl?

Pickling Medium
A. open("model.pkl", "wb")
B. open("model.pkl", "rb")
C. open("model.pkl", "r")
D. 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)

Handling the ZeroDivisionError exception Medium
A. Cannot divide
B. 0
C. ValueError
D. 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")

Using try-except blocks Medium
A. ValueError, printing Invalid number
B. TypeError, printing no message
C. ZeroDivisionError, printing Zero is not allowed
D. NameError, printing no message

31 When does the else block associated with a Python try-except statement execute?

The else block Medium
A. When the try block finishes without an exception
B. When the try block raises every listed exception
C. When the finally block is omitted from the statement
D. When any except block finishes handling an exception

32 Which structure handles a missing settings.txt file while allowing other input/output errors to propagate?

Handling the FileNotFoundError exception Medium
A. try: open("settings.txt") followed by except FileNotFoundError:
B. try: open("settings.txt") followed by except IOError:
C. try: open("settings.txt") followed by except RuntimeError:
D. 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?

Concept of regular expressions Medium
A. It prevents Python from processing the backslash as a string escape
B. It makes the regular expression ignore whitespace automatically
C. It forces the pattern to match only at the string beginning
D. It converts every matched digit into a raw integer value

34 Which pattern matches a product code containing exactly two uppercase letters followed by exactly three digits?

Various types of regular expressions Medium
A. r"^[A-Z]{2}\d{3}$"
B. r"^[A-Z]{3}\d{2}$"
C. r"^[a-z]{2}\d{3}$"
D. r"^[A-Z]+\d+$"

35 Which regular expression matches either color or colour, but not colouur?

Various types of regular expressions Medium
A. r"colou+r"
B. r"colou*r"
C. r"colou?r"
D. r"colo.r"

36 What is the result of re.match(r"\d+", "ID: 123")?

Using the match function Medium
A. A match containing ID
B. A match containing 123
C. None
D. A match containing ID: 123

37 What does result.group(2) return after this code runs?

result = re.match(r"([A-Za-z]+)-(\d+)", "Item-204")

Using the match function Medium
A. "204"
B. "Item-204"
C. "-204"
D. "Item"

38 Given html = '<a href="/home">Home</a><a href="/help">Help</a>', which expression extracts both URL values?

Web scraping using regular expressions Medium
A. re.match(r'href="([^"]+)"', html)
B. re.split(r'href="([^"]+)"', html)
C. re.findall(r'href="([^"]+)"', html)
D. 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?

Web scraping using regular expressions Medium
A. r"<p>*</p>"
B. r"<p>(.*)</p>"
C. r"<p>(.*?)</p>"
D. r"<p>.+</p>"

40 A page source contains <title>Python\nGuide</title>. Which call captures the title text even though it spans two lines?

Web scraping using regular expressions Medium
A. re.findall(r"^<title>(.*?)</title>$", html)
B. re.match(r"<title>(.*?)</title>", html, re.MULTILINE)
C. re.search(r"<title>(.*?)</title>", html, re.DOTALL)
D. 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?

Text files Hard
A. The data is written only if the file already exists
B. Python normally closes the file during interpreter shutdown, but explicit closing is safer
C. The data is always permanently lost
D. The file remains locked permanently after program termination

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?

Writing variables Hard
A. It writes 7 because integers are automatically converted
B. It raises ValueError; use f.write(int(x))
C. It raises TypeError; use f.write(str(x))
D. It writes the binary representation of the integer

43 A file contains alpha\nbeta\n. After lines = f.readlines(), which result is produced when the file is opened in normal text mode?

Reading from a file Hard
A. ["alpha", "beta"]
B. ["alpha", "beta", ""]
C. "alpha\nbeta\n"
D. ["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?

Writing to a file Hard
A. The operation raises FileExistsError
B. A\nB\nC\n
C. C\nA\nB\n
D. C\n

45 Which statement best explains why os.mkdir("reports/2025/january") can fail even when the current directory exists?

Directories Hard
A. os.mkdir() works only with absolute paths
B. os.mkdir() creates only one directory level
C. Directories can contain only files
D. Python forbids directory names containing digits

46 Why is loading an untrusted file with pickle.load() considered unsafe?

Pickling Hard
A. Unpickling may execute attacker-controlled code
B. Pickle always stores data in plain-text format
C. Unpickling silently converts every object to a string
D. Pickle files cannot preserve nested objects

47 A program pickles an object containing a class instance, then the class definition is renamed before unpickling. What is the most likely result?

Pickling Hard
A. The object is converted automatically into a dictionary
B. The pickle automatically updates the class name
C. The object is always reconstructed normally
D. Unpickling may fail because the original importable class path is unavailable

48 What does the following code print? try: print(10 / 0)\nexcept ZeroDivisionError: print("invalid")\nprint("done")

Handling the ZeroDivisionError exception Hard
A. done followed by invalid
B. invalid followed by done
C. Only invalid
D. The program terminates before either message

49 What is the main problem with writing except Exception: around an entire file-processing program without logging or re-raising the exception?

Using try-except blocks Hard
A. It catches only syntax errors
B. It automatically retries every failed file operation
C. It can hide unrelated defects and make failures difficult to diagnose
D. It prevents all exceptions from being raised by Python

50 For the code try: value = int("3.5")\nexcept ValueError: value = 0, what is the final value of value?

Using try-except blocks Hard
A. The variable remains undefined
B. 0 because integer conversion rejects decimal text
C. 3.5 as a floating-point value
D. 3 as an integer

51 In a try-except-else construct, when does the else block execute?

The else block Hard
A. Only when the try block completes without an exception
B. Only when an exception is caught
C. Whenever the try block begins
D. After the finally block regardless of failure

52 Why is f.write(result) often placed in the else block after successfully opening and reading a file?

The else block Hard
A. It ensures writing occurs only when the protected read operation succeeded
B. It makes the else block execute before the try block
C. It causes the file to be opened in append mode
D. It guarantees that writing cannot raise an exception

53 A program uses open("input.txt", "r") inside a try block and catches FileNotFoundError. Which situation can still cause a different exception?

Handling the FileNotFoundError exception Hard
A. The file name contains alphabetic characters
B. The file does not exist
C. The file is opened in read mode
D. The path refers to a directory instead of a regular file

54 Which design best avoids accidentally destroying a file when a program intends to update it only after successfully reading its contents?

Handling the FileNotFoundError exception Hard
A. Use "r+" and assume failed reads leave all content unchanged
B. Read it first, then open it in "w" mode for replacement
C. Open it in "a" mode and overwrite from the beginning
D. Open it in "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?

Concept of regular expressions Hard
A. Exactly four hyphens surrounding eight optional digits
B. Exactly four digits, two digits, and two digits separated by hyphens
C. A year followed by arbitrary alphabetic text
D. Any string containing a date-like substring

56 Which pattern correctly matches a Python identifier that begins with a letter or underscore and continues with letters, digits, or underscores?

Various types of regular expressions Hard
A. ^[_A-Za-z]\d*$
B. ^[A-Za-z_]\w*$
C. ^[A-Za-z0-9]+$
D. ^\w+[A-Za-z_]$

57 What is the practical difference between the patterns a+ and a* when matching a string?

Various types of regular expressions Hard
A. Both patterns require exactly one a
B. a* matches only the literal character *
C. a+ permits zero or one a, while a* requires one
D. 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")?

Using the match function Hard
A. match succeeds at the beginning; search finds cat later
B. match finds all occurrences; search finds only the first character
C. match ignores order; search requires the pattern at index zero
D. Both fail because 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?

Using the match function Hard
A. Named groups cannot be combined with numbered groups
B. m.group("area") is the complete string only
C. m.group("area") is "212" and m.group(2) is "5555"
D. 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?

Web scraping using regular expressions Hard
A. Regular expressions cannot contain capture groups
B. HTML permits nesting, optional attributes, entities, and varied whitespace that the pattern may not model
C. HTML is always binary data and cannot be searched as text
D. The pattern can match only numeric URLs