Introduction to Computer Science/1.5: Fixing a Common Bug (Type Casting)

1.5: Fixing a Common Bug (Type Casting)

🎯 Learning Goals for This Page
  • Recognize that the input() function always gives you a string.
  • Understand that trying to do math with a string will cause a TypeError.
  • Use int() and float() to convert strings into numbers for calculations.

The input() Problem: A Tale of Two Types

There is a critical "gotcha" with the input() function that every new programmer encounters: no matter what the user types, it always gives you back a string. This can lead to some surprising (and frustrating) bugs.

Live Example: Watch it Break!

The code in the Trinket below looks like it should work. Click the Run â–¶ button, enter a birth year (like 2008), and press Enter. Notice that it crashes! Read on to understand why.

Python 3Initializing...
Loading code editor...
Program output will appear here...

The program crashed with a TypeError. This is Python's way of saying you tried to perform an operation on the wrong type of data. We tried to subtract a string ("2008") from a number (2025). It's like trying to calculate 2025 - "hello". It doesn't make sense.


The Solution: Type Casting

To fix this, we must explicitly convert the data from one type to another. This is called type casting. We use functions that match the type we want:

  • int(value): Converts the value to an integer.
  • float(value): Converts the value to a floating-point number.
  • str(value): Converts the value to a string.

Here is what the corrected line of code looks like:

# We wrap the input() function directly inside int()
birth_year_int = int(input("What year were you born? "))

Your Turn to Be the Debugger!

Go back to the Trinket window above. Your challenge is to fix the broken code. Wrap the input() function inside the int() function just like the example shows. Run the program again. If you do it right, the program will work perfectly!

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...