PCEP-30-02 practice question 20 of 35

What is the output of the following code snippet if the user enters a 0? try: val = input('Enter a value: ') print(int(val) / len(val)) except ZeroDivisionError: print('ZeroDivisionError raised...') except: print('Bad input...')

Full set: 548 questions

Domain Functions and Exceptions

Answer options
A: This code will raise the ValueError exception and output Bad input... to the console.
B: 0.0 Correct answer
C: This code will raise the ZeroDivisionError exception and output ZeroDivisionError raised... to the console.
D: This code will raise the TypeError exception and output Bad input... to the console.
Correct Answer:
B. 0.0
Explanation

When the user enters 0, the input() function captures this as the string '0'. The variable val is therefore assigned the string '0'. The expression inside the print() function is then evaluated:
1. int(val) converts the string '0' to the integer 0.
2. len(val) calculates the length of the string '0', which is 1.
3. The division 0 / 1 is performed. In Python 3, this division results in a float, 0.0. Since no error occurs during these operations, the try block completes successfully, and the except blocks are skipped. The final output is 0.0.

Why Incorrect

A. A ValueError is not raised because int('0') is a valid operation; this exception would occur for non-numeric strings like 'a'.
C. A ZeroDivisionError is not raised because the divisor, len('0'), evaluates to 1, not 0.
D. A TypeError is not raised because all functions and operators are used with compatible data types.

References

1. Python 3.12.3 Documentation, "Built-in Functions":

input([prompt]): "The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that." This confirms val will be the string '0'.

len(s): "Return the length (the number of items) of an object." For a string, this is the number of characters. len('0') is 1.

int(x): "Return an integer object constructed from a number or string x...". This confirms int('0') successfully returns the integer 0.

2. Python 3.12.3 Documentation, "The try statement," Section 8.3:

"If no exception occurs in the try clause, no exception handler is executed." This supports why the except blocks are skipped in this scenario.

3. MIT OpenCourseWare, 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016, Lecture 5: Tuples, Lists, Aliasing, Mutability, Cloning:

The lecture materials on exception handling explain that the code within a try block is executed first. If it runs without raising an exception, the except blocks are ignored, and execution continues after the try...except structure. This principle directly applies to the given problem.

Scroll to Top