PCEP-30-02 · Question #245
QUESTION 273 What is the expected behavior of the following program if the user enters 0? value = input("Enter a value: ") print(10/value)
The correct answer is C. The program will raise the TypeError exception. C is correct because Python's input() function always returns a string, so when the user enters 0, value holds the string "0", not the integer 0. Attempting 10 / "0" means dividing an int by a str - incompatible types - which raises a TypeError. Why the distractors fail: A…
Question
Options
- AThe program will raise the ZeroDivisionError exception
- BThe program will raise the ValueError exception
- CThe program will raise the TypeError exception
- DThe program will output 0 to the console
How the community answered
(33 responses)- A9% (3)
- B3% (1)
- C82% (27)
- D6% (2)
Explanation
C is correct because Python's input() function always returns a string, so when the user enters 0, value holds the string "0", not the integer 0. Attempting 10 / "0" means dividing an int by a str - incompatible types - which raises a TypeError.
Why the distractors fail:
- A (ZeroDivisionError) would occur only if
valuewere the integer0, which would require something likeint(input(...))- the missing type conversion is the whole trap here. - B (ValueError) arises when a conversion itself fails (e.g.,
int("hello")), not from a type mismatch in an operation. - D (outputs 0) is never reached; the exception is thrown before any output occurs.
Memory tip: In Python 3, input() is always a string - no exceptions. Whenever you see raw input() used in arithmetic, immediately think "type mismatch = TypeError." If the code had cast it with int(), then you'd think about ZeroDivisionError.
Community Discussion
No community discussion yet for this question.