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. Computer hardware settings
B. Only executable programs
C. Only image data
D. Human-readable characters

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

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

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

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

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

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

5 Which method writes a string to an open file?

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

6 Which Python module provides functions for working with directories?

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

7 Which function creates a new directory in Python?

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

8 What is pickling in Python?

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

9 Which Python module is commonly used for pickling objects?

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

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

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

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

Handling the ZeroDivisionError exception Easy
A. A return statement
B. A try-except block
C. A continue statement
D. A print 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 closes the program
C. Only code that runs after success
D. Code that may raise an exception

13 What is the purpose of an except block?

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

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

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

15 When is FileNotFoundError commonly raised?

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

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

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

17 What is a regular expression?

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

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

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

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

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

20 How can regular expressions help with web scraping?

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

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: ", score])
B. file.write("Score: " + str(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. 0
B. 3
C. 2
D. 1

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", "w")
B. open("log.txt", "r")
C. open("log.txt", "x")
D. open("log.txt", "a")

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.make("data", "report.txt")
C. os.join.path("data", "report.txt")
D. os.path.join("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.chdir("results/2025/june")
C. os.mkdir("results/2025/june")
D. os.makedirs("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 file.read() twice and convert each result
B. Call pickle.load(file) twice in the same order
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", "rb")
B. open("model.pkl", "r")
C. open("model.pkl", "a")
D. open("model.pkl", "wb")

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. 0
B. ValueError
C. Cannot divide
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. TypeError, printing no message
B. NameError, printing no message
C. ZeroDivisionError, printing Zero is not allowed
D. ValueError, printing Invalid number

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

The else block Medium
A. When the finally block is omitted from the statement
B. When any except block finishes handling an exception
C. When the try block finishes without an exception
D. When the try block raises every listed 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 RuntimeError:
B. try: open("settings.txt") followed by except FileNotFoundError:
C. try: open("settings.txt") followed by except IOError:
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 makes the regular expression ignore whitespace automatically
B. It converts every matched digit into a raw integer value
C. It forces the pattern to match only at the string beginning
D. It prevents Python from processing the backslash as a string escape

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]+\d+$"
D. r"^[a-z]{2}\d{3}$"

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. None
B. A match containing 123
C. A match containing ID: 123
D. A match containing ID

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.findall(r'href="([^"]+)"', html)
B. re.match(r'href="([^"]+)"', html)
C. re.split(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.search(r"<title>(.*?)</title>", html, re.DOTALL)
C. re.match(r"<title>(.*?)</title>", html, re.MULTILINE)
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 always permanently lost
B. Python normally closes the file during interpreter shutdown, but explicit closing is safer
C. The data is written only if the file already exists
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 raises ValueError; use f.write(int(x))
B. It raises TypeError; use f.write(str(x))
C. It writes the binary representation of the integer
D. It writes 7 because integers are automatically converted

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\n", "beta\n"]
B. ["alpha", "beta"]
C. "alpha\nbeta\n"
D. ["alpha", "beta", ""]

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. C\nA\nB\n
B. A\nB\nC\n
C. C\n
D. The operation raises FileExistsError

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. Python forbids directory names containing digits
C. Directories can contain only files
D. os.mkdir() creates only one directory level

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

Pickling Hard
A. Unpickling silently converts every object to a string
B. Unpickling may execute attacker-controlled code
C. Pickle always stores data in plain-text format
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. Unpickling may fail because the original importable class path is unavailable
B. The object is converted automatically into a dictionary
C. The pickle automatically updates the class name
D. The object is always reconstructed normally

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

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

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 automatically retries every failed file operation
B. It prevents all exceptions from being raised by Python
C. It catches only syntax errors
D. It can hide unrelated defects and make failures difficult to diagnose

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. 3.5 as a floating-point value
C. 3 as an integer
D. 0 because integer conversion rejects decimal text

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

The else block Hard
A. Whenever the try block begins
B. Only when an exception is caught
C. Only when the try block completes without an exception
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 guarantees that writing cannot raise an exception
B. It causes the file to be opened in append mode
C. It ensures writing occurs only when the protected read operation succeeded
D. It makes the 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?

Handling the FileNotFoundError exception Hard
A. The file does not exist
B. The file name contains alphabetic characters
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 "w" mode before attempting the read
D. Open it in "a" mode and overwrite from the beginning

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 digits, two digits, and two digits separated by hyphens
B. Any string containing a date-like substring
C. A year followed by arbitrary alphabetic text
D. Exactly four hyphens surrounding eight optional digits

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-z0-9]+$
B. ^[A-Za-z_]\w*$
C. ^[_A-Za-z]\d*$
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+ permits zero or one a, while a* requires one
C. a* matches only the literal character *
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 ignores order; search requires the pattern at index zero
B. match succeeds at the beginning; search finds cat later
C. Both fail because cat is not the whole string
D. match finds all occurrences; search finds only the first character

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

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. The pattern can match only numeric URLs
B. Regular expressions cannot contain capture groups
C. HTML permits nesting, optional attributes, entities, and varied whitespace that the pattern may not model
D. HTML is always binary data and cannot be searched as text