PCEP-30-02 · Question #274
The user enters 123. Which of the following code snippets will print 124 to the monitor? (Choose three.)
Options B, C, and D correctly print 124, because each one ensures the input is converted to an integer before arithmetic is performed. input() in Python 3 always returns a string, so "123" + 1 in Option A raises a TypeError - you cannot add an integer to a string directly…
Question
Options
- Anum = input('Please enter your number: ') print(num + 1)
- Bnum = int(input('Please enter your number: ')) print(num + 1)
- Cnum = eval(input('Please enter your number: ')) print(num + 1)
- Dnum = input('Please enter your number: ') print(int(num) + 1)
Explanation
Options B, C, and D correctly print 124, because each one ensures the input is converted to an integer before arithmetic is performed. input() in Python 3 always returns a string, so "123" + 1 in Option A raises a TypeError - you cannot add an integer to a string directly, making A the one distractor. Option B converts at the point of input using int(), Option C uses eval() which evaluates the string "123" as a Python expression and returns the integer 123, and Option D stores the raw string but converts it with int() at print time - all three result in 123 + 1 = 124.
Memory tip: Think of input() as always handing you a string in quotes - "123" is not the same as 123. Any time you need math, you must unwrap the quotes with int(), float(), or eval() before or during the operation, not after.
Community Discussion
No community discussion yet for this question.