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. Human-readable characters
B. Only image data
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. int()
B. list()
C. open()
D. str()

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

Reading from a file Easy
A. remove()
B. write()
C. close()
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. a
C. w
D. r

5 Which method writes a string to an open file?

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

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.file()
C. os.open()
D. os.mkdir()

8 What is pickling in Python?

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

9 Which Python module is commonly used for pickling objects?

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

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

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

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

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

12 What code is placed inside the try block?

Using try-except blocks Easy
A. Only code that closes the program
B. Only comments about 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 repeat a loop
C. To handle an exception
D. To define a new variable

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

The else block Easy
A. When no exception occurs
B. When every 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 requested file is missing
B. When a string is printed
C. When a number is divided by zero
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. FileNotFoundError
B. ZeroDivisionError
C. IndexError
D. KeyError

17 What is a regular expression?

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

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

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

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

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

20 How can regular expressions help with web scraping?

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

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\n", "blue\n"]
B. "red blue"
C. ("red", "blue")
D. ["red", "blue"]

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: " + str(score))
C. file.write(["Score: ", score])
D. file.write("Score: " + 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. 3
B. 2
C. 0
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", "r")
B. open("log.txt", "w")
C. open("log.txt", "a")
D. open("log.txt", "x")

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

Directories Medium
A. os.path.make("data", "report.txt")
B. os.join.path("data", "report.txt")
C. os.path.concat("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.mkdir("results/2025/june")
B. os.chdir("results/2025/june")
C. os.makedirs("results/2025/june")
D. os.listdir("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) once to obtain both objects
C. Call pickle.load(file) twice in the same order
D. Call pickle.loads(file) twice in reverse order

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. 20
B. Cannot divide
C. ValueError
D. 0

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. ZeroDivisionError, printing Zero is not allowed
C. ValueError, printing Invalid number
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 any except block finishes handling an exception
B. When the try block raises every listed exception
C. When the try block finishes without an exception
D. When the finally block is omitted from the statement

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 Exception:
C. try: open("settings.txt") followed by except RuntimeError:
D. try: open("settings.txt") followed by except IOError:

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]+\d+$"
C. r"^[A-Z]{3}\d{2}$"
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"colo.r"
B. r"colou*r"
C. r"colou+r"
D. r"colou?r"

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

Using the match function Medium
A. None
B. A match containing ID: 123
C. A match containing ID
D. A match containing 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. "Item-204"
B. "Item"
C. "-204"
D. "204"

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.search(r"<title>(.*?)</title>", html, re.ASCII)
C. re.search(r"<title>(.*?)</title>", html, re.DOTALL)
D. re.match(r"<title>(.*?)</title>", html, re.MULTILINE)

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 file remains locked permanently after program termination
B. Python normally closes the file during interpreter shutdown, but explicit closing is safer
C. The data is always permanently lost
D. The data is written only if the file already exists

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 TypeError; use f.write(str(x))
B. It writes the binary representation of the integer
C. It raises ValueError; use f.write(int(x))
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", "beta", ""]
B. "alpha\nbeta\n"
C. ["alpha", "beta"]
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. C\n
B. The operation raises FileExistsError
C. A\nB\nC\n
D. C\nA\nB\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. Directories can contain only files
C. os.mkdir() creates only one directory level
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. Unpickling silently converts every object to a string
C. Pickle files cannot preserve nested objects
D. Pickle always stores data in plain-text format

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 pickle automatically updates the class name
B. The object is always reconstructed normally
C. The object is converted automatically into a dictionary
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. The program terminates before either message
B. done followed by invalid
C. Only 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 can hide unrelated defects and make failures difficult to diagnose
B. It prevents all exceptions from being raised by Python
C. It automatically retries every failed file operation
D. It catches only syntax errors

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

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

The else block Hard
A. Only when an exception is caught
B. Only when the try block completes without an exception
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 guarantees that writing cannot raise an exception
C. It causes the file to be opened in append mode
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 path refers to a directory instead of a regular file
B. The file does not exist
C. The file name contains alphabetic characters
D. The file is opened in read mode

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. Read it first, then open it in "w" mode for replacement
B. Use "r+" and assume failed reads leave all content unchanged
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 digits, two digits, and two digits separated by hyphens
B. A year followed by arbitrary alphabetic text
C. Exactly four hyphens surrounding eight optional digits
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. ^\w+[A-Za-z_]$
B. ^[_A-Za-z]\d*$
C. ^[A-Za-z0-9]+$
D. ^[A-Za-z_]\w*$

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

Various types of regular expressions Hard
A. a* matches only the literal character *
B. a+ permits zero or one a, while a* requires one
C. Both patterns require exactly one a
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. Both fail because cat is not the whole string
C. match succeeds at the beginning; search finds cat later
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. Regular expressions cannot contain capture groups
B. The pattern can match only numeric URLs
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