A developer writes a script that prompts the user for their age and stores it in a variable. Which code snippet correctly converts the input to an integer?
Trap 1: age = int(input)
int(input) passes the built-in function object itself to int(), which raises TypeError rather than converting text. It is tempting because input is the function that reads console data, but conversion requires calling it first: int(input()).
Trap 2: age = input("Enter age: ", int)
input() accepts only a prompt argument; passing int as a second argument raises TypeError, and no conversion occurs. It is tempting because int appears alongside input, but the integer conversion must wrap the returned string: int(input("Enter age: ")).
Trap 3: age = input(int("Enter age: "))
int("Enter age: ") attempts to convert the literal prompt text to an integer, raising ValueError before input() ever runs. It is tempting because it nests the two functions, but the correct order calls input() first, then wraps its result in int().
- A
age = int(input)
Why it fails: int(input) passes the built-in function object itself to int(), which raises TypeError rather than converting text. It is tempting because input is the function that reads console data, but conversion requires calling it first: int(input()).
- B
age = int(input("Enter age: "))
The int() constructor parses the string returned by input() and returns an integer object, so age holds a numeric value usable in arithmetic. Without the cast, input() always yields a string, which would break numeric comparisons.
- C
age = input("Enter age: ", int)
Why it fails: input() accepts only a prompt argument; passing int as a second argument raises TypeError, and no conversion occurs. It is tempting because int appears alongside input, but the integer conversion must wrap the returned string: int(input("Enter age: ")).
- D
age = input(int("Enter age: "))
Why it fails: int("Enter age: ") attempts to convert the literal prompt text to an integer, raising ValueError before input() ever runs. It is tempting because it nests the two functions, but the correct order calls input() first, then wraps its result in int().