CHapter 8

Ace your homework & exams now with Quizwiz!

Which of the following statements is true for built-in exceptions?

A built-in exception can be called in a code using a 'raise' statement.

Which of following modules would warrant the use of the reload() function in a script?

A module that scrapes off data from a list of websites which are updated every day.

What is output? def print_number(a):try:print('{0:.2f}'.format(a))except:print('Cannot print the value')print_number('10')print_number(2.0)

Cannot print the value 2.00

Which of the following directories is contained in sys.path?

The directory where Python is installed.

What happens when a raise statement is encountered in a function?

The function is exited with no return.

data.csv:Product Name, PricePen, 10Pencil, 20Eraser, 5 What is output? import csvwith open('data.csv','r+') as file:csvFile = csv.reader(file)for row in csvFile:print(row)

['Product Name', ' Price'] ['Pen', ' 10'] ['Pencil', ' 20'] ['Eraser', ' 5']

What is output? from math import (pi, exp, log)import urllibprint(__name__)

__main__

Which of the following functions creates a sequence of 50 bytes?

bytes(50)

Which of the following statements provides the path to a module named circle.py?

circle.__file__

Which of the following is a good example of the definition of a custom exception type?

class InputError(Exception):def __init__(self, value):self.value = value

Which XXX is the correct example for defining a custom exception? XXXtry:f = 'Myfile.txt'ext = f.split('.').pop()if (ext == 'txt'):raise InvalidFileTypeError('Invalid File Type')except Exception as e:print(e)finally:print('All done!')

class InvalidFileTypeError(Exception):def __init__(self, value):self.value = value

Identify the code that generates 'os' as output.

import osprint(os.__name__)

A custom exception type is usually defined by:

inheriting from the exception class.

Identify the function that handles the exception. def Division(a, b):return (a / b)def Sum(a, b):return (a + b)def main():a = 200.0b = 0.0try:Sum(a, b)Division(a, b)except:print('Error Occurred')main()

main()

Replace x and y with the correct module to generate the following output. Calculation done on: *actual date* 36.0 from x import powimport ytoday_date = y.date.today()base = 6exponent = 2print('Calculation done on:', today_date)print(pow(base, exponent))

math, datetime

A _____ is a namespace that contains definitions from the module.

module object

Which is the correct syntax for opening a file in Python?

my_file = open('Wikipedia_data.txt')

Which of the following statements reads up to 100 bytes from a file named student.txt?

my_file = open('student.txt')line = my_file.read(100)

Which XXX generates 'Error Occurred' as the output? def larger(a, b=1):if a > b: return a else:return b XXX except:print('Error Occurred')

try:print(larger('21', 33))print(larger(20))

A(n) _____ should be used to specify all the exception types when being handled by a single exception handler.

tuple

Which of the following is a good name for a new custom module?

url.py

Which of the following is true for an environment variable?

It can be accessed by every program running on the computer

Which of the following statements is the reason for avoiding the use of a catch-all except clause?

To make sure that no bug is hidden under the catch-all except block

Which of the following statements is not true for importing a module:

If the module has already been loaded, then a new namespace is created and its codes are executed.

_____ can be set to specify optional directories where modules are located.

PYTHONPATH

Which statement opens a file for appending?

file = open('ABC.txt', 'a')

Which of the following statements imports an entire module named ABC?

import ABC

If __name__ == '__main__' is true, then ______.

the file is being executed as a script

Which of the following statements prints the last field in each row of the csv file?

with open('my_file.csv', 'r') as f:csv_data = csv.reader(f)for r in csv_data:print(r[-1])

What is output? def get_name(name):if len(name) <= 2:raise ValueError('You need to enter your complete name.')return namedef get_age(age):if age > 100:raise ValueError('Please enter some value')return agetry:name = get_name('Mike')school_name = get_age('3')print('{} is {} years old.'.format(name, school_name))except ValueError as excpt:print(excpt)except:print('Error!')

Error!

What is the output if the input is '0'? class MyDivideByZeroError(Exception):def __init__(self, value):self.value = valueException.__init__(self, value)print('Enter a number\n')num = int(input())try:if num == 0:raise MyDivideByZeroError('Number needs to be greater than zero!\n')exitelse:num = num / 0print('Your number after dividing by zero: ', my_num)except MyDivideByZeroError:print('My Exception raised')except:print('Oops! An unknown error occurred.\n')

My Exception raised

Which of the following is added into the global namespace after running the from ABC import (length, breadth) import statement?

Only the length and breadth attributes of ABC.

What is output? def division(a, b):try:div = a / bprint('Quotient: {}'.format(div))except:print('Cannot divide {} by {}'.format(a, b))division(10, 2)division(2, 0)division('13',2)

Quotient: 5.0 Cannot divide 2 by 0 Cannot divide 13 by 2

What happens when an unhandled exception occurs?

The finally clause executes, and then the exception is re-raised.

Consider the following my_script.py. What is the output when the command-line argument python my_script.py input.txt output.txt is run on the terminal?

['my_script.py', 'input.txt', 'output.txt'] 12

The reload() function returns the _____.

namespace of the module with updated definitions

Complete the code to append the values in my_list to a file named my_data.txt with one value in each line. my_list = [10, 20, 30, 50]XXX

file = open('my_data.txt', 'a+')for i in my_list:file.write(str(i) + '\n')

Which of the following methods forces the output buffer to write to disk?

flush() and close()

Identify the correct package import statement for print('Area = {}'.format(Shapes.Square.dimensions.area(a))) .

import Shapes

Consider a package, Shapes, that contains the modules square.py, rectangle.py, and circle.py. Which of the following statements should be used to import rectangle.py?

import Shapes.rectangle

Identify the correct import statement for the following code: print('The sum of values is: {}'.format(calculate.sum(10, 20)))

import calculate

Identify the module file circle.py for the given code that will generate the following output. Radius is 6 Area: 113.10 from circle import (area, radius)if __name__ == '__main__':a = area(6)print('Area: {0:.2f}'.format(a))

import mathdef area(r):print(radius(r))return math.pi * r * rdef radius(r):return('Radius is {}'.format(r))if __name__ == '__main__':print(radius, area)

Which of the following statements pauses code execution for 5 seconds?

import timetime.sleep(5)

If the module urllib has not been loaded, which of the following statements causes the new module object to be created and added to sys.modules?

import urllib

Which of the following libraries is used to retrieve the current working directory?

os

Which function returns a numeric output?

os.path.getsize()

If /Users/ABC/script.txt is the path to a file, which statement returns True as a value?

os.path.isfile('/Users/ABC/script.txt')

Which function is used to create a portable file path string by concatenating the strings using the correct path separator?

os.path.join()

A(n) _____ is a directory that gives access to all of the modules stored in a directory when imported.

package

Which of the following statements causes a ValueError to occur?

raise Value error

For a function print_names() imported in a code, which of the following statements is the correct syntax to reload that function in the same code?

reload(print_names)

A programmer will typically write a(n) _____ and pass it to the interpreter.

script

It is recommended to use a 'with' statement when opening files so that ____.

the file is closed when no longer needed

Which of the following standard libraries can be used to convert time zones?

time

Choose the code that produces 'Thank you!' as output.

try:n = 0for i in range(n):print('Square of {} is {}'.format(i,i * i))except:print('Wrong value!')finally:print('Thank you!')

Which of the following standard libraries is used to access a file stored on a website?

urllib

What is output? def division(a, b):try:div = a / bprint('Quotient: {}'.format(div))except (TypeError, ZeroDivisionError):print('Invalid Input!')except (ValueError):print('Invalid Input Value!')division(2, 0)division('2', 10)division(36.0, 5.0)

Invalid Input! Invalid Input! Quotient: 7.2

What is output? time = 0 distance = 0 try:if time <= 0: raise ValueError('Invalid Time!') if distance <= 0:raise ValueError('Speed: 0') speed = distance / time print('Speed: {}'.format(speed)) except ValueError as expt: print(expt) print('Cannot calculate speed.')

Invalid Time! Cannot calculate speed.

What is output? def odd_even(a):if isinstance(a, int):if a % 2 == 0:return 'even'else:return 'odd'else:raise TypeError('Invalid Variable Type!') try:n = '3'print(odd_even(n))except TypeError as expt:print(expt)except:print('Error!')finally:print('Value entered:', n)

Invalid Variable Type! Value entered: 3

Complete the code to handle the exception and to generate 'Error Occurred'. new_string = 'Python'my_index = 0try:while my_index != len(new_string) / 2:print(new_string[my_index:len(new_string)/2])my_index += lXXXprint('Error Occurred')

except (TypeError, IndentationError):

Which XXX generates the following output? Division by zero 100 50 33 25

except ZeroDivisionError as e:print(e)

Python uses _________ constructs to handle errors during execution.

exception-handling

A comma separated values (csv) file is a simple text-based file format that uses commas to separate _____.

fields

Identify the loop that prints the names of the directories, subdirectories, and files in a path.

for dirname, subdirs, files in os.walk(path):print(dirname, subdirs, files)

Consider a module file named Rectangle containing functions calc_area() and length(). Which option is the right way to import only these functions?

from Rectangle import (calc_area, length)print(calc_area(5, 10))

Identify the code that generates 'The value of pi is: 3.14' as output.

from math import piprint('The value of pi is: {0:.2f}'.format(pi))

Consider the following my_script.py. Which statement should replace XXX in the script for the command-line argument python my_script.py input.txt ? import sysimport osif len(sys.argv) != 2:print('Usage: {} inputfile '.format(sys.argv[0]))sys.exit(1)print('Opening file {}...'.format(sys.argv[1]))XXXprint('Oh No! The file does not exist.')sys.exit(1)

if not os.path.exists(sys.argv[1]):

Identify the correct syntax for importing modules from the script readFile.py?

import readFile

The Numbers.txt file contains a list of integer numbers. Complete the code to print the sum of the numbers in the file. f = open('Numbers.txt')lines = f.readlines()f.close()XXXprint(sum)

sum = 0for i in lines:sum += int(i)

my_list.txt: 150+250 Which of the following code blocks writes the sum in a new line of the file?

with open('my_list.txt', 'r+') as file:line = file.readline()sum = 0for i in line.split('+'):sum = sum + int(i)file.write(str(sum))

Which XXX is used to write data in the file? import csvrow1 = ['1', '2', '3']row2 = ['Tina', 'Rita', 'Harry']XXXstudents_writer = csv.writer(csvfile)students_writer.writerow(row1)students_writer.writerow(row2)students_writer.writerows([row1, row2])

with open('students.csv', 'w') as csvfile:

The _____ keyword binds a name to the exception being handled.

as

A python code only runs the except block when _____.

an error occurs in the preceding try block

The with statement creates a(n) _____ which performs setup and teardown operations.

context manager

Which of the following is the correct syntax for a multiple exception handler?

except (NameError, AttributeError):

Which could be the name of the function for the import statement from Shapes.Square.dimensions import area

area

Complete the code to generate 'Remainder: 0.0' as output. def Remainder(a, b):if b == 0:return(b % a)else:return(a % b)XXXfinally:print('Remainder:', z)

try:a = 20b = 0z = Remainder(a, b)except:print('Wrong value entered')


Related study sets

APEH Unit 2: Reformation and Religious Wars

View Set

MAGIC TIME - How are you ? - What's your name?

View Set

Chapter 14: Pricing Concepts for Establishing Value

View Set

Wordsmart I and II only words(Partial Bangla), Word Smart for the GRE (2nd Ed)

View Set

Anthropology Human Origins Exam 2

View Set

Fuentes Primarias y Secundarias 1

View Set

MIDTERM EXAM 1: DATABASE MANAGEMENT SYS Chapter 1

View Set