Question Detail

COS 102 Python strings Objective Question

Question

How can a TypeError be avoided when you need to combine a string and a number in Python?
Options
A By enclosing the number in parentheses
B By using the `int()` function on the string
C By converting the number to a string first using `str()`
Correct Answer
D By separating them with a comma instead of '+'
Correct Answer

Option C is the correct answer.

Detailed Explanation

The document's 'The Fix' for TypeError states, 'Convert the number to a string first using str().' For example, "Age: " + str(20).

Hint

The solution involves ensuring both operands of the '+' operator are strings.

Question Info