The Secret Life of Python: The Silent Type (Type Casting)
Source: Dev.to
The Problem
Timothy wrote a simple guessing game, but even when he typed the correct number, the program told him he was wrong.
# Timothy's Guessing Game
secret_number = 7
guess = input("Guess the number (1-10): ")
if guess == secret_number:
print("You won! Amazing!")
else:
print(f"Sorry, you guessed {guess}, but the number was {secret_number}.")
Output
Guess the number (1-10): 7
Sorry, you guessed 7, but the number was 7.
Why It Happens: Strong Typing in Python
input()always returns a string (str).secret_numberis an integer (int).
Python does not perform implicit type conversion when comparing values of different types. The comparison guess == secret_number is therefore False because '7' (a string) is not the same as 7 (an integer).
Analogy: Comparing a photograph of a dog to the real dog—both look similar, but they are fundamentally different objects.
The Fix: Explicit Type Casting
Wrap the input() call with int() (or another appropriate cast) to convert the entered text to an integer.
# Timothy's Fixed Game
secret_number = 7
# Convert the input string to an integer
guess = int(input("Guess the number (1-10): "))
if guess == secret_number:
print("You won! Amazing!")
else:
print(f"Sorry, you guessed {guess}, but the number was {secret_number}.")
Output
Guess the number (1-10): 7
You won! Amazing!
Important Note
If the user types a non‑numeric word like "seven", int() will raise a ValueError. Handling such cases gracefully (e.g., with try/except or validation) is a topic for a later lesson.
Quick Reference: Common Casts
int("5")→5(whole number)float("5")→5.0(decimal number)str(5)→"5"(useful for concatenation or printing)
Attempting int("hello") will raise a ValueError.
Takeaways
- Rule:
input()returns a string, regardless of what the user types. - Fix: Use explicit type casting (
int(),float(), etc.) to match the expected data type. - Benefit: Python’s strict typing prevents accidental operations on mismatched types, encouraging clearer, more reliable code.
Looking Ahead
In the next episode, Timothy will encounter “The Phantom Copy”, where copying a list leads to unexpected changes in the backup—a classic case of mutable object references.