Convert the Answer
Convert the player's string input to an integer
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
The correct variable holds the integer 3. But input() always returns a string — if the player types 3, Python stores the text "3", not the number 3. You cannot meaningfully compare a string to an integer, so you need to convert the player's answer before you can use it.
The int() function
int() converts a value to an integer. Pass a string containing a number and it returns the number itself:
age_text = "25"
age = int(age_text)
print(age) # 25
print(type(age)) # <class 'int'>The original variable is not changed. int() returns a new value, which you store in a separate variable.
If the string contains anything that isn't a valid integer — like "hello" or "3.5" — int() raises an error and the program crashes. A real quiz needs to catch that and ask again. You'll handle that properly in the next course using try/except.
Instructions
Convert the player's string input to an integer.
- After
answer_text = input(...), create a variable namedanswerand assign itint(answer_text)—correctis the integer3, and you cannot compare a string to an integer, so the conversion makes the comparison possible in the next chapter.
question = "What is the type of the value 3.14?"
option_1 = "int"
option_2 = "str"
option_3 = "float"
option_4 = "bool"
correct = 3
print("=== Python Quiz ===")
print()
print(question)
print()
print(f" 1) {option_1}")
print(f" 2) {option_2}")
print(f" 3) {option_3}")
print(f" 4) {option_4}")
print()
answer_text = input("Your answer (1-4): ")
# Step 1: Create answer variable
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding