A developer writes code to compute the average of two numbers entered by the user: x = input('Enter first number: '); y = input('Enter second number: '); avg = (x + y) / 2. The program produces an error. What is the best practice to fix the code?
This ensures the addition and division work on numeric values.
Why this answer
The `input()` function in Python always returns a string. When you use the `+` operator on two strings, it concatenates them (e.g., '5' + '3' = '53'), not adds them numerically. Dividing a concatenated string by 2 raises a TypeError.
The best practice is to convert both inputs to `float` immediately after receiving them, ensuring the subsequent arithmetic works correctly.
Exam trap
Python Institute often tests the misconception that `input()` returns a numeric type, leading candidates to pick Option B (using `int`) or Option C (casting inside the expression), but the trap is that string concatenation happens before any conversion, so the error occurs at the `+` operator, not at the division.
How to eliminate wrong answers
Option A is wrong because it attempts to convert the result after the operation, but the error occurs earlier: `x + y` concatenates strings, and dividing a string by 2 raises a TypeError, so `int()` never executes. Option B is wrong because converting to `int` truncates any decimal input (e.g., 5.5 becomes 5), losing precision; for an average, `float` is more appropriate. Option C is wrong because while it converts inside the expression, it still concatenates strings first (`x + y` before `float()` is applied), causing the same TypeError; the conversion must happen before the addition.