Register Login

TypeError unsupported operand type(s) for + 'int' and 'str'

Updated Mar 30, 2024

A common error that is encountered in python is "TypeError unsupported operand type(s) for + 'int' and 'str'". This happens when the two or more values that you are trying to add are not of the same data type.

The best way to fix this is to add the values that have the same data type. In this article, we will look at the different scenarios where you might encounter this error. Then we will find ways to fix it.

How to fix it?

In order to fix this, you can convert the variables to have the same data type.

For example, you can convert a string into an int by:

int(variable)

Examples of TypeError unsupported operand type(s) for + 'int' and 'str'

Example 1

Let us consider the following piece of code:

# Python program to add two values
val1 = 10
val2 = '12'

# Add two values
out = val1 + val2
print('Sum of two values: ',out)

Output:

out = val1 + val2
TypeError: unsupported operand type(s) for +: 'int' and 'str'

In the above example you are trying to add an integer and a string. This is not possible. 

val1 = 10 ## Declared as Integer
val2 = '12' ## Declared as string

Correct Code:

# Python program to add two values
val1 = 10
val2 = 12

# Add two values
out = val1 + val2
print('Sum of two values: ',out)

TypeError unsupported operand type(s) for + 'int' and 'str'

Example 2

Let us consider the following piece of code:

# Enter three integer value to create list
int1= int(input("Enter First Integer: "))
int2 = int(input("Enter Second Integer:"))
int3 = int(input("Enter Third Integer: "))

# Add all interger value in list
intlist = [int1, int2, int3]

# Print Integer List
print('List Created: ',intlist)
print("Remove Second Element from List")
print(intlist.pop(2) + " Second Element has Removed from List")
print("New List: " + str(intlist))

Output

After entering all the values of the variables int1, int2 and int3, the code returns this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

You encounter this error as you are trying to add an integer and a string. This is not possible. You have to change this line print(intlist.pop(2) + " Second Element has Removed from List"). Change it using any of these processes described below:

print(intlist.pop(2)," Second Element has Removed from List")

or

You can use string formatting like this:

print("{} Second Element has Removed from List".format(intlist.pop(2)))

Correct Code:

# Enter three integer value to create list
int1= int(input("Enter First Integer: "))
int2 = int(input("Enter Second Integer:"))
int3 = int(input("Enter Third Integer: "))

# Add all interger value in list
intlist = [int1, int2, int3]

# Print Integer List
print('List Created: ',intlist)
print("Remove Second Element from List")
print(intlist.pop(2), " Second Element has Removed from List")
print("New List: " + str(intlist))

 


×