Deck 9: Files and Exceptions
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Unlock Deck
Sign up to unlock the cards in this deck!
Unlock Deck
Unlock Deck
1/30
Play
Full screen (f)
Deck 9: Files and Exceptions
1
When a Python program begins execution, it creates three xe "file object:standard"xe "standard file objects"standard file objects: sys.stdin-the standard input file object,
sys.stdout-the standard output file object, and
sys.stderr-the standard error file object.
You must import the sys module if you need to refer to these objects explicitly in your code, but this is rare. Which of the following statements is false?
A) Though these are considered file objects, they do not read from or write to files by default.
B) The input function implicitly uses sys.stdin to get user input from the keyboard.
C) Function print implicitly outputs to sys.stdout, which appears in the command line.
D) Python implicitly outputs program errors and tracebacks to sys.stdout.
sys.stdout-the standard output file object, and
sys.stderr-the standard error file object.
You must import the sys module if you need to refer to these objects explicitly in your code, but this is rare. Which of the following statements is false?
A) Though these are considered file objects, they do not read from or write to files by default.
B) The input function implicitly uses sys.stdin to get user input from the keyboard.
C) Function print implicitly outputs to sys.stdout, which appears in the command line.
D) Python implicitly outputs program errors and tracebacks to sys.stdout.
Python implicitly outputs program errors and tracebacks to sys.stdout.
2
Which of the following statements are false?
A) The built-in open function opens a file and associates it with a xe "file object"file object.
B) The mode argument specifies the file-open mode, indicating whether to open a file for reading from the file, for writing to the file or both.
C) The mode 'w' xe "open a file:for writing"opens the file for writing, creating the file if it does not exist. If the file already exists, opening it for writing causes any new data to be appended to the end of the file.
D) At the end of the with statement's suite, the with statement implicitly calls the file object's close method to close the file.
A) The built-in open function opens a file and associates it with a xe "file object"file object.
B) The mode argument specifies the file-open mode, indicating whether to open a file for reading from the file, for writing to the file or both.
C) The mode 'w' xe "open a file:for writing"opens the file for writing, creating the file if it does not exist. If the file already exists, opening it for writing causes any new data to be appended to the end of the file.
D) At the end of the with statement's suite, the with statement implicitly calls the file object's close method to close the file.
C
3
Which of the following statements is false?
A) Many applications xe "resource:acquire"xe "acquire resources"acquire resources, such as files, network connections, database connections and more. You should xe "resource:release"xe "release resources"release resources when your application terminates.
B) The with statement acquires a resource and assigns its corresponding object to a variable.
C) The with statement allows the application to use the resource via that variable.
D) The with statement calls the resource object's xe "close method:of an object that uses a system resource"close method to release the resource when program control reaches the end of the with statement's suite.
A) Many applications xe "resource:acquire"xe "acquire resources"acquire resources, such as files, network connections, database connections and more. You should xe "resource:release"xe "release resources"release resources when your application terminates.
B) The with statement acquires a resource and assigns its corresponding object to a variable.
C) The with statement allows the application to use the resource via that variable.
D) The with statement calls the resource object's xe "close method:of an object that uses a system resource"close method to release the resource when program control reaches the end of the with statement's suite.
A
4
The json module's ________ function reads the entire JSON contents of its file object argument and converts the JSON into a Python object. This is known as ________ the data.
A) read, serializing
B) load, serializing
C) load, deserializing
D) read, deserializing
A) read, serializing
B) load, serializing
C) load, deserializing
D) read, deserializing
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
5
Which of the following statements a), b) or c) is false?
A) You can use JSON to serialize and deserialize objects to facilitate saving those objects to secondary storage and transmitting them over the Internet.
B) There are security vulnerabilities to serializing and deserializing data with the Python Standard Library's pickle module.
C) The with statement automatically releases a resource at the end of the statement's suite.
D) All of the above statements are true.
A) You can use JSON to serialize and deserialize objects to facilitate saving those objects to secondary storage and transmitting them over the Internet.
B) There are security vulnerabilities to serializing and deserializing data with the Python Standard Library's pickle module.
C) The with statement automatically releases a resource at the end of the statement's suite.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
6
Which of the following statements a), b) or c) is false?
A) Variables, lists, tuples, dictionaries, sets, arrays, pandas Series and pandas DataFrames offer long-term data storage.
B) Computers store files on secondary storage devices, including xe "solid-state drive"solid-state drives, xe "hard disk"hard disks and more.
C) Some popular text file formats are plain text, xe "JSON (JavaScript Object Notation)"JSON (JavaScript Object Notation) and xe "CSV (comma-separated value) format"CSV (comma-separated values).
D) All of the above statements are true?
A) Variables, lists, tuples, dictionaries, sets, arrays, pandas Series and pandas DataFrames offer long-term data storage.
B) Computers store files on secondary storage devices, including xe "solid-state drive"solid-state drives, xe "hard disk"hard disks and more.
C) Some popular text file formats are plain text, xe "JSON (JavaScript Object Notation)"JSON (JavaScript Object Notation) and xe "CSV (comma-separated value) format"CSV (comma-separated values).
D) All of the above statements are true?
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
7
Which of the following statements a), b) or c) is false?
A) The following code writes an object in JSON format to a file: import json
With open('accounts.json', 'w') as accounts:
Json.dump(accounts_dict, accounts)
B) The snippet in Part (a) opens the file accounts.json and uses the json module's dump function to serialize the dictionary accounts_dict into the file.
C) JSON delimits strings with double-quote characters.
D) All of the above statements are true.
A) The following code writes an object in JSON format to a file: import json
With open('accounts.json', 'w') as accounts:
Json.dump(accounts_dict, accounts)
B) The snippet in Part (a) opens the file accounts.json and uses the json module's dump function to serialize the dictionary accounts_dict into the file.
C) JSON delimits strings with double-quote characters.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
8
Which of the following statements a), b) or c) is false?
A) JSON objects are similar to Python lists. Each xe "JSON (JavaScript Object Notation):JSON object"JSON object contains a comma-separated list of property names and values, in curly braces. For example, the following JSON object might represent a client record: {"account": 100, "name": "Jones", "balance": 24.98}
B) JSON also supports xe "JSON (JavaScript Object Notation):array"xe "array:JSON"arrays which, like Python lists, are comma-separated values in square brackets. For example, the following is an acceptable JSON array of numbers: [100, 200, 300]
C) Values in JSON objects and arrays can be xe "JSON (JavaScript Object Notation):string"xe "string built-in type:in JSON"strings in double quotes, numbers, JSON xe "JSON (JavaScript Object Notation):Boolean values"xe "Boolean values in JSON"Boolean values (xe "JSON (JavaScript Object Notation):true"true or xe "JSON (JavaScript Object Notation):false"false),xe "JSON (JavaScript Object Notation):null"xe "null in JSON" null (to represent no value, like None in Python), arrays and other JSON objects.
D) All of the above statements are true.
A) JSON objects are similar to Python lists. Each xe "JSON (JavaScript Object Notation):JSON object"JSON object contains a comma-separated list of property names and values, in curly braces. For example, the following JSON object might represent a client record: {"account": 100, "name": "Jones", "balance": 24.98}
B) JSON also supports xe "JSON (JavaScript Object Notation):array"xe "array:JSON"arrays which, like Python lists, are comma-separated values in square brackets. For example, the following is an acceptable JSON array of numbers: [100, 200, 300]
C) Values in JSON objects and arrays can be xe "JSON (JavaScript Object Notation):string"xe "string built-in type:in JSON"strings in double quotes, numbers, JSON xe "JSON (JavaScript Object Notation):Boolean values"xe "Boolean values in JSON"Boolean values (xe "JSON (JavaScript Object Notation):true"true or xe "JSON (JavaScript Object Notation):false"false),xe "JSON (JavaScript Object Notation):null"xe "null in JSON" null (to represent no value, like None in Python), arrays and other JSON objects.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
9
The json module enables you to convert objects to xe "JSON (JavaScript Object Notation)"JSON (JavaScript Object Notation) text format. This is known as ________ the data.
A) chunking
B) calibrating
C) serializing
D) registering
A) chunking
B) calibrating
C) serializing
D) registering
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
10
Which of the following statements are false?
A) A file object's readlines method xe "read a file into a program"reads an entire text file and returns each line as a string in a list of strings.
B) Calling readlines for a large file can be a time-consuming operation, which must complete before you can begin using the list of strings.
C) Using the file object in a for statement enables your program to process each text line as it's read.
D) All of the above statements are true.
A) A file object's readlines method xe "read a file into a program"reads an entire text file and returns each line as a string in a list of strings.
B) Calling readlines for a large file can be a time-consuming operation, which must complete before you can begin using the list of strings.
C) Using the file object in a for statement enables your program to process each text line as it's read.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
11
Which of the following statements is false?
A) For a text file, the read method returns a string containing the number of characters specified by the method's integer argument. For a binary file, the method returns the specified number of bytes. If no argument is specified, the method returns the entire contents of the file.
B) The readline method returns one line of text as a string, including the newline character if there is one.
C) The readline method issues an EndOfFileError when it encounters the end of the file.
D) The writelines method receives a list of strings and writes its contents to a file.
A) For a text file, the read method returns a string containing the number of characters specified by the method's integer argument. For a binary file, the method returns the specified number of bytes. If no argument is specified, the method returns the entire contents of the file.
B) The readline method returns one line of text as a string, including the newline character if there is one.
C) The readline method issues an EndOfFileError when it encounters the end of the file.
D) The writelines method receives a list of strings and writes its contents to a file.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
12
Which of the following statements is false?
A) Attempting to divide by 0 results in a xe "ZeroDivisionError"ZeroDivisionError.
B) When a program attempts to divide by zero, the interpreter is said to raise an exception of type xe "ZeroDivisionError"ZeroDivisionError.
C) When an exception is raised in an interactive IPython session, it displays the exception's traceback, then terminates the IPython session.
D) If an exception occurs in a script, IPython terminates the script and displays the exception's traceback.
A) Attempting to divide by 0 results in a xe "ZeroDivisionError"ZeroDivisionError.
B) When a program attempts to divide by zero, the interpreter is said to raise an exception of type xe "ZeroDivisionError"ZeroDivisionError.
C) When an exception is raised in an interactive IPython session, it displays the exception's traceback, then terminates the IPython session.
D) If an exception occurs in a script, IPython terminates the script and displays the exception's traceback.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
13
Which of the following statements a), b) or c) is false?
A) Python views text files and binary files (for images, videos and more) as xe "sequence:of bytes"sequences of bytes.
B) As in lists and arrays, the first character in a text file and byte in a binary file is located at position 0, so in a file of n characters or bytes, the highest position number is n - 1.
C) For each file you open, Python creates a file object that you'll use to interact with the file.
D) All of the above statements are true.
A) Python views text files and binary files (for images, videos and more) as xe "sequence:of bytes"sequences of bytes.
B) As in lists and arrays, the first character in a text file and byte in a binary file is located at position 0, so in a file of n characters or bytes, the highest position number is n - 1.
C) For each file you open, Python creates a file object that you'll use to interact with the file.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
14
Which of the following statements a), b) or c) is false?
A) The json module's dumps function returns a Python string representation of an object in JSON format.
B) Using dumps with load, you can read JSON from a file and display it in a nicely indented format-sometimes called "pretty printing" the JSON.
C) When the dumps function call includes the indent keyword argument, as in with open('accounts.json', 'r') as accounts:
Print(json.dumps(json.load(accounts), indent=4))
The string contains newline characters and indentation for pretty printing-you also can use indent with the dump function when writing to a file:
D) All of the above statements are true.
A) The json module's dumps function returns a Python string representation of an object in JSON format.
B) Using dumps with load, you can read JSON from a file and display it in a nicely indented format-sometimes called "pretty printing" the JSON.
C) When the dumps function call includes the indent keyword argument, as in with open('accounts.json', 'r') as accounts:
Print(json.dumps(json.load(accounts), indent=4))
The string contains newline characters and indentation for pretty printing-you also can use indent with the dump function when writing to a file:
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
15
Which of the following statements are false?
A) Many libraries you'll use to interact with xe "cloud-based services"cloud-based services such as Twitter, IBM Watson and others communicate with your applications via JSON (JavaScript Object Notation) objects.
B) JSON is a dxe "JSON (JavaScript Object Notation):data-interchange format"xe "data-interchange format:JSON"ata-interchange format readable only by computers and used to represent objects (such as dictionaries, lists and more) as collections of name-value pairs.
C) JSON can represent objects of custom classes.
D) JSON has become the preferred data format for transmitting objects across platforms. This is especially true for invoking cloud-based xe "web service"web services, which are functions and methods that you call over the Internet.
A) Many libraries you'll use to interact with xe "cloud-based services"cloud-based services such as Twitter, IBM Watson and others communicate with your applications via JSON (JavaScript Object Notation) objects.
B) JSON is a dxe "JSON (JavaScript Object Notation):data-interchange format"xe "data-interchange format:JSON"ata-interchange format readable only by computers and used to represent objects (such as dictionaries, lists and more) as collections of name-value pairs.
C) JSON can represent objects of custom classes.
D) JSON has become the preferred data format for transmitting objects across platforms. This is especially true for invoking cloud-based xe "web service"web services, which are functions and methods that you call over the Internet.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
16
If the contents of a file should not be modified, open the file for ________-another example of the xe "principle of least privilege"principle of least privilege. This prevents the program from accidentally modifying the file.
A) writing only
B) reading only
C) reading and writing
D) none of the above
A) writing only
B) reading only
C) reading and writing
D) none of the above
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
17
Various types of exceptions can occur when you work with files. Which of the following statements a), b) or c) is false?
A) A FileNotFoundError occurs if you attempt to open a non-existent file for reading with the 'r' or 'r+' modes.
B) A PermissionsError occurs if you attempt an operation for which you do not have permission. This might occur if you try to open a file that your account is not allowed to access or create a file in a folder where your account does not have permission to write, such as where your computer's operating system is stored.
C) A LockedError (with the error message 'I/O operation on closed file.') occurs when you attempt to write to a file that has already been closed.
D) All of the above statements are true.
A) A FileNotFoundError occurs if you attempt to open a non-existent file for reading with the 'r' or 'r+' modes.
B) A PermissionsError occurs if you attempt an operation for which you do not have permission. This might occur if you try to open a file that your account is not allowed to access or create a file in a folder where your account does not have permission to write, such as where your computer's operating system is stored.
C) A LockedError (with the error message 'I/O operation on closed file.') occurs when you attempt to write to a file that has already been closed.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
18
Which of the following statements a), b) or c) is false?
A) The Python Standard Library's pickle module can serialize objects into the data formats of many popular programming languages.
B) Pickle has potential security issues.
C) If you write your own pickling and de-pickling code, pickling can be secure.
D) All of the above statements are true.
A) The Python Standard Library's pickle module can serialize objects into the data formats of many popular programming languages.
B) Pickle has potential security issues.
C) If you write your own pickling and de-pickling code, pickling can be secure.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
19
Which of the following statements a), b) or c) is false?
A) The file open modes for writing and appending raise a FileNotFoundError if the file does not exist.
B) Each text-file mode has a corresponding binary-file mode specified with b, as in 'rb' or 'wb+'.
C) You use binary-file modes for reading or writing binary files, such as images, audio, video, compressed ZIP files and many other popular custom file formats.
D) All of the above statements are true.
A) The file open modes for writing and appending raise a FileNotFoundError if the file does not exist.
B) Each text-file mode has a corresponding binary-file mode specified with b, as in 'rb' or 'wb+'.
C) You use binary-file modes for reading or writing binary files, such as images, audio, video, compressed ZIP files and many other popular custom file formats.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
20
Which of the following statements a), b) or c) is false?
A) Python imposes a convenient record structure on files.
B) The following code creates an accounts.txt file and writes five client records to the file. Generally, records in text files are stored one per line, so we end each record with a newline character: with open('accounts.txt', mode='w') as accounts:
Accounts.write('100 Jones 24.98\n')
Accounts.write('200 Doe 345.67\n')
Accounts.write('300 White 0.00\n')
Accounts.write('400 Stone -42.16\n')
Accounts.write('500 Rich 224.62\n')
C) You can also write to a file with print (which automatically outputs a \n), as in print('100 Jones 24.98', file=accounts)
D) All of the above statements are true.
A) Python imposes a convenient record structure on files.
B) The following code creates an accounts.txt file and writes five client records to the file. Generally, records in text files are stored one per line, so we end each record with a newline character: with open('accounts.txt', mode='w') as accounts:
Accounts.write('100 Jones 24.98\n')
Accounts.write('200 Doe 345.67\n')
Accounts.write('300 White 0.00\n')
Accounts.write('400 Stone -42.16\n')
Accounts.write('500 Rich 224.62\n')
C) You can also write to a file with print (which automatically outputs a \n), as in print('100 Jones 24.98', file=accounts)
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
21
b. When there are except handlers, program control transfers to the first one that matches the type of the raised exception. If there are no except handlers that match the raised exception, a process called xe "stack:unwinding"stack unwinding occurs.
c. When an except clause successfully handles an exception, program execution resumes with the finally clause (if there is one), then with the next statement after the try statement.
d. After an exception is handled, program control returns to the xe "raise point"raise point.
Answer: d. Actually, after an exception is handled, program control does not return to the xe "raise point"raise point-rather, control resumes after the try statement.
9.8.3 xe "multiple-exception catching[multiple exception catching]"xe "except clause:catching multiple exceptions"xe "catching multiple exceptions in one except clause"Catching Multiple Exceptions in One except Clause
Which of the following statements is false?
A) A try clause is often followed by several except clauses to handle various types of exceptions.
B) When no exceptions occur in the try suite, program execution resumes with the xe "else clause:of a try statement"else clause (if there is one); otherwise, program execution resumes with the next statement after the try statement.
C) If several except suites are identical, you can catch those exception types by specifying them as a tuple in a single except handler, as in: except [type1, type2, …] as variable_name
D) You can use the variable name in the optional as-clause to reference the exception object in the except suite.
c. When an except clause successfully handles an exception, program execution resumes with the finally clause (if there is one), then with the next statement after the try statement.
d. After an exception is handled, program control returns to the xe "raise point"raise point.
Answer: d. Actually, after an exception is handled, program control does not return to the xe "raise point"raise point-rather, control resumes after the try statement.
9.8.3 xe "multiple-exception catching[multiple exception catching]"xe "except clause:catching multiple exceptions"xe "catching multiple exceptions in one except clause"Catching Multiple Exceptions in One except Clause
Which of the following statements is false?
A) A try clause is often followed by several except clauses to handle various types of exceptions.
B) When no exceptions occur in the try suite, program execution resumes with the xe "else clause:of a try statement"else clause (if there is one); otherwise, program execution resumes with the next statement after the try statement.
C) If several except suites are identical, you can catch those exception types by specifying them as a tuple in a single except handler, as in: except [type1, type2, …] as variable_name
D) You can use the variable name in the optional as-clause to reference the exception object in the except suite.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
22
The int function raises a ________ if you attempt to convert to an integer a string (like 'hello') that does not represent a number.
A) NameError
B) ConversionError
C) ValueError
D) None of the above
A) NameError
B) ConversionError
C) ValueError
D) None of the above
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
23
Which of the following statements a), b) or c) is false?
A) Most resources that require explicit release, such as files, network connections and database connections, have potential exceptions associated with processing those resources.
B) A program that processes a file might raise IOErrors. For this reason, robust file-processing code normally appears in a try suite containing a with statement to guarantee that the resource gets released.
C) When a with statement is in a try suite, you can catch in except handlers any exceptions that occur and you do not need a finally clause because the with statement handles resource deallocation.
D) All of the above statements are true.
A) Most resources that require explicit release, such as files, network connections and database connections, have potential exceptions associated with processing those resources.
B) A program that processes a file might raise IOErrors. For this reason, robust file-processing code normally appears in a try suite containing a with statement to guarantee that the resource gets released.
C) When a with statement is in a try suite, you can catch in except handlers any exceptions that occur and you do not need a finally clause because the with statement handles resource deallocation.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
24
Which of the following statements is false?
A) A try clause may be followed by one or more except clauses that immediately follow the try clause's suite.
B) The except clauses also are known as xe "exception:handler"exception handlers.
C) Each xe "except clause"except clause specifies the type of exception it handles.
D) After the last except clause, an optional else clause specifies code that should execute only if the code in the try suite raised an exception.
A) A try clause may be followed by one or more except clauses that immediately follow the try clause's suite.
B) The except clauses also are known as xe "exception:handler"exception handlers.
C) Each xe "except clause"except clause specifies the type of exception it handles.
D) After the last except clause, an optional else clause specifies code that should execute only if the code in the try suite raised an exception.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
25
Which of the following statements a), b) or c) is false?
A) When the finally clause terminates, program control continues with the next statement after the try statement. In an IPython session, the next In [] prompt appears.
B) The following code includes a try statement in which an exception occurs in the try suite: try:
Print('try suite that raises an exception')
Int('hello')
Print('this will not execute')
Except ValueError:
Print('a ValueError occurred')
Else:
Print('else will not execute because an exception occurred')
Finally:
Print('finally always executes')
C) The xe "finally:clause"finally clause executes only when an exception occurs in the corresponding try suite.
D) All of the above statements are true.
A) When the finally clause terminates, program control continues with the next statement after the try statement. In an IPython session, the next In [] prompt appears.
B) The following code includes a try statement in which an exception occurs in the try suite: try:
Print('try suite that raises an exception')
Int('hello')
Print('this will not execute')
Except ValueError:
Print('a ValueError occurred')
Else:
Print('else will not execute because an exception occurred')
Finally:
Print('finally always executes')
C) The xe "finally:clause"finally clause executes only when an exception occurs in the corresponding try suite.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
26
Which of the following statements a), b) or c) is false?
A) Operating systems typically can prevent more than one program from manipulating a file at once.
B) When a program finishes processing a file, the program immediately should close it to release the resource. This enables other programs to use the file (if they're allowed to access it).
C) Closing a file creates a resource leak in which the file resource is not available to other programs.
D) All of the above statements are true.
A) Operating systems typically can prevent more than one program from manipulating a file at once.
B) When a program finishes processing a file, the program immediately should close it to release the resource. This enables other programs to use the file (if they're allowed to access it).
C) Closing a file creates a resource leak in which the file resource is not available to other programs.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
27
The following code uses exception handling to xe "except clause"catch and xe "handle (or resolve) an exception"handle any ValueErrors and ZeroDivisionErrors that arise. 1 while True:
2 try:
3 number1 = int(input('Enter numerator: '))
4 number2 = int(input('Enter denominator: '))
5 result = number1 / number2
6 except ValueError:
7 print('You must enter two integers\n')
8 except ZeroDivisionError:
9 print('Attempted to divide by zero\n')
10 else:
11 print(f'{number1:.3f} / {number2:.3f} = {result:.3f}')
12 break
Where in the code could either or both of these errors arise?
A) line 3
B) line 5
C) lines 3 and 4
D) lines 3, 4 and 5
2 try:
3 number1 = int(input('Enter numerator: '))
4 number2 = int(input('Enter denominator: '))
5 result = number1 / number2
6 except ValueError:
7 print('You must enter two integers\n')
8 except ZeroDivisionError:
9 print('Attempted to divide by zero\n')
10 else:
11 print(f'{number1:.3f} / {number2:.3f} = {result:.3f}')
12 break
Where in the code could either or both of these errors arise?
A) line 3
B) line 5
C) lines 3 and 4
D) lines 3, 4 and 5
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
28
Which of the following statements is false?
A) A try statement can have a finally clause as its last clause after any except clauses or else clause.
B) The finally clause is guaranteed to execute, regardless of whether its try suite executes successfully or an exception occurs.
C) In other languages that have finally, the finally suite is an ideal location to place resource-deallocation code for resources acquired in the corresponding try suite.
D) In Python, we prefer the else clause of a try statement for resource-deallocation code and place other kinds of "clean up" code in the finally suite.
A) A try statement can have a finally clause as its last clause after any except clauses or else clause.
B) The finally clause is guaranteed to execute, regardless of whether its try suite executes successfully or an exception occurs.
C) In other languages that have finally, the finally suite is an ideal location to place resource-deallocation code for resources acquired in the corresponding try suite.
D) In Python, we prefer the else clause of a try statement for resource-deallocation code and place other kinds of "clean up" code in the finally suite.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
29
Which of the following statements a), b) or c) is false?
A) Wrap a separate try statement around every individual statement that raises an exception.
B) For proper exception-handling granularity, each try statement should enclose a section of code small enough that, when an exception occurs, the specific context is known and the except handlers can process the exception properly.
C) If many statements in a try suite raise the same exception types, multiple try statements may be required to determine each exception's context.
D) All of the above statements are true.
A) Wrap a separate try statement around every individual statement that raises an exception.
B) For proper exception-handling granularity, each try statement should enclose a section of code small enough that, when an exception occurs, the specific context is known and the except handlers can process the exception properly.
C) If many statements in a try suite raise the same exception types, multiple try statements may be required to determine each exception's context.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck
30
Which of the following statements is false?
a. When an exception occurs in a try suite, it terminates immediately.
a. When an exception occurs in a try suite, it terminates immediately.
Unlock Deck
Unlock for access to all 30 flashcards in this deck.
Unlock Deck
k this deck