Conquer Python's TypeError! An Easy Guide to Beating "Mismatched Types" Errors
Hello! The person writing this article was a complete beginner just a few months ago, someone who didn't know the first thing about programming. With the help of AI, I now run two websites on my own.
While learning to program, everyone eventually runs into those red error messages. "TypeError", in particular, can be really confusing and discouraging at first. I've been there too.
But don't worry. In this article, based on my own stumbling blocks, I'll explain "What is a TypeError?" and "How can I fix it?" in the simplest way possible, avoiding jargon as much as I can. By the time you finish reading this, you'll no longer fear TypeErrors; you'll see them as helpful "allies" that give you clues to a solution!
First of all, what is a "TypeError"? π€
Let's start with a quick quiz. Can you do the following calculation?
"the number 10" + "the word 'dollars'"
Intuitively, you might think "10 dollars." Now, how about this?
"the number 10" + "the word 'apples'"
...You can't really calculate that, can you? "10 apples"? It doesn't make sense as a calculation.
Actually, Python struggles with the exact same problem. To Python, a number (in technical terms, `int` or `float`) and a word (in technical terms, `str`) are completely different things. Just as a person can't add "the number 10" and "the word 'apples'," Python panics when you try to mix different kinds of data in a calculation, thinking, "I don't know which type to use for this calculation!"
This "panic due to mismatched types" is the true identity of a `TypeError`. The error message is a kind sign telling us, "Master! The Type of data you're trying to calculate is different, so it's an Error!"
[Practice] Let's Experience and Defeat a Common TypeError!
Now that you have a rough idea of the theory, let's experience a `TypeError` with actual code and see the process of fixing it. Just by following these step-by-step instructions, you'll get the hang of solving errors.
Case 1: Trying to connect a number and a string with "+"
First, let's look at the most common pattern. Suppose you wrote the following code to create a sentence stating your age.
β Code that causes an error
If you copy and run this code, a `TypeError` will occur.
age = 30
print("I am " + age + " years old.")
# Execution result:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: can only concatenate str (not "int") to str
There it is, the `TypeError`. Let's look at the end of the error message.TypeError: can only concatenate str (not "int") to str
This means, "You can only concatenate (join) a `str` (string) to another `str` (not an `int` (integer)!)." Python is telling us, "I can't directly add the string 'I am ' and the number `30`!"
π΅οΈββοΈ Investigating the cause: Let's check if the types are really different
We've figured out the cause of the error is "mismatched types." Now, let's ask Python directly to confirm it. To check a variable's type, we can use the handy `type()` function.
text = "I am "
age = 30
print( type(text) )
print( type(age) )
# Execution result:
# <class 'str'>
# <class 'int'>
As you can see, `text` is a string (`str`) and `age` is an integer (`int`). This confirms that the types are indeed different.
β Solution 1: Transform the number into a string with `str()`
Once you know the cause, the rest is easy. We just need to transform the number `age` into a string. The magic for that is the `str()` function. By wrapping a variable in `str()`, you can convert any type into a string.
age = 30
# Use str() to convert the integer 'age' to a string!
print("I am " + str(age) + " years old.")
# Execution result:
# I am 30 years old.
We did it! It displayed correctly without any errors. This is the basic way to defeat a `TypeError`.
β Solution 2 (Recommended): Solve it smartly with f-strings!
You can solve it with `str()`, but there's a more modern and readable way. It's called an "f-string".
Just put an `f` before the opening quotation mark of the string and enclose the variable name in curly braces `{}`. That's all it takes for Python to automatically convert the variable to a string and embed it nicely. There's no need to join with `+` or convert with `str()`.
age = 30
# Using an f-string makes it so clean!
print(f"I am {age} years old.")
# Execution result:
# I am 30 years old.
What do you think? This way, the code is shorter, more intuitive, and easier to understand. From now on, I highly recommend using f-strings when combining strings and variables!
Case 2: The `input()` trap with user input
In websites and apps, there are many situations where you need to get input from a user. To receive user input in Python, you use the `input()` function, but there's a big pitfall here.
β Code that causes an error
Let's write code that asks the user for their birth year and calculates their current age (as of 2025).
birth_year = input("Please enter your birth year (e.g., 1995): ")
age = 2025 - birth_year
print(f"You are {age} years old!")
# Execution (e.g., entering 1995):
# Please enter your birth year (e.g., 1995): 1995
#
# Execution result:
# Traceback (most recent call last):
# File "<stdin>", line 2, in <module>
# TypeError: unsupported operand type(s) for -: 'int' and 'str'
Another `TypeError`. This time the message is unsupported operand type(s) for -: 'int' and 'str'. It's saying, "For the `-` (subtraction) operation, the combination of `int` (number) and `str` (string) is not supported."
You might be thinking, "Huh? I entered 1995, so why is it a string?" This is the crucial point.
Any value received from the `input()` function is treated as a string (`str`), even if it looks like a number.
This is an absolute rule in Python, so it's best to memorize it. A quick check with `type()` makes it crystal clear.
birth_year = input("Please enter your birth year (e.g., 1995): ")
print(f"The type of the input data is: {type(birth_year)}")
# Execution (e.g., entering 1995):
# Please enter your birth year (e.g., 1995): 1995
#
# Execution result:
# The type of the input data is: <class 'str'>
β Solution: Transform the string into a number with `int()`
The cause was that `birth_year` became a string (`str`) because of `input()`. To perform a calculation, we need to transform it into a number (`int`).
That's where the `int()` function comes in. It's the opposite of `str()`. Let's wrap the value received from `input()` entirely in `int()`.
# Immediately convert the result of input() to an integer with int()!
birth_year_str = input("Please enter your birth year (e.g., 1995): ")
birth_year_int = int(birth_year_str)
age = 2025 - birth_year_int
print(f"You are about {age} years old!")
# Execution (e.g., entering 1995):
# Please enter your birth year (e.g., 1995): 1995
#
# Execution result:
# You are about 30 years old!
It calculated perfectly! When you use `input()`, convert it with `int()` before calculating. If you remember this combo, you'll have nothing to fear.
[Learning in the AI Era] Just Ask an AI About Your TypeError!
The reason I was able to move past the beginner stage of programming so quickly was because I had AI as my partner. Even if an error message appears, there's no need to panic. Today, you have a brilliant AI assistant by your side at all times.
When you get an error, copy the "code that caused the error" and the "full error message" and try asking an AI like this:
[The Magic Prompt (Question)]
When I ran the following Python code, I got an error.
Please explain the cause of this error and how to fix it in a way that's easy for a programming beginner to understand, using specific examples.
βΌ Code
```python
# Paste your code that caused the error here
age = 30
print("I am " + age + " years old.")
```
βΌ Error Message
```
# Paste the full error message here
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
```
If you ask like this, the AI should patiently explain "why the error occurred" and "how to fix it," just as I've explained in this article. Let's make the most of AI as the ultimate learning tool that turns errors into opportunities for growth!
Summary: TypeError is Your Friend π€
This time, we've covered the identity and defeat of the `TypeError` that trips up so many beginners. Finally, let's review the key points.
- Cause of TypeError: Trying to calculate with different types of data mixed together.
- First thing to do: Check the type of suspicious variables with the `type()` function.
- Solution: Use `str()` or `int()` to make the types match (type conversion).
- The `input()` rule: The value received from `input()` is always a string (`str`).
- Recommended practice: When combining strings and variables, f-strings are by far the easiest and most readable.
- Your strongest ally: If you get an error, copy and paste the code and error message to an AI!
An error is a kind hint that points out a mistake in your code. Once you can see a `TypeError` and think, "Okay, time to check the types," you've graduated from being a beginner. You'll encounter many more errors in the future, but by solving them one by one, you will definitely level up. I'm rooting for you!
To the Next Step
For you who have mastered `TypeError`. Next, why not challenge another tricky error, "garbled text," which you often encounter when reading or writing files? Once you understand the cause, this one isn't scary either.
Next Article: How to Deal with UnicodeDecodeError (Garbled Text) »