In python, TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ error occurs when an integer value is added to a variable that is None. You can add an integer number with a another number. You can’t add a number to None. The Error TypeError: unsupported operand type(s) for +: ‘int’ and ‘NoneType’ will be thrown if an integer value is added with an operand or an object that is None.
An mathematical addition is performed between two numbers. It may be an integer, a float, a long number, etc. The number can not be added to the operand or object that is None. None means that no value is assigned to the variable. So if you try to add a number to a variable that is None, the error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be thrown.
Objects other than numbers can not be used for arithmetic operations such as addition , subtraction, etc. If you try to add a number to a variable that is None, the error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be displayed. The None variable should be assigned to an integer before it is added to another number.
Exception
The error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be shown as below the stack trace. The stack trace shows the line where an integer value is added to a variable that is None.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x + y
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
[Finished in 0.0s with exit code 1]
How to reproduce this error
If you try to add an integer value with a variable that is not assigned to a value, the error will be reproduced. Create two python variables. Assign a variable that has a valid integer number. Assign another variable to None. Add the two variables to the arithmetic addition operator.
x = None
y = 2
print x + y
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 3, in <module>
print x + y
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
[Finished in 0.0s with exit code 1]
Root Cause
In Python, the arithmetic operation addition can be used to add two valid numbers. If an integer value is added with a variable that is assigned with None, this error TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’ will be thrown. The None variable should be assigned a valid number before it is added to the integer value.
Solution 1
If an integer value is added with a variable that is None, the error will be shown. A valid integer number must be assigned to the unassigned variable before the mathematical addition operation is carried out. This is going to address the error.
x = 3
y = 2
print x + y
Output
5
[Finished in 0.1s]
Solution 2
If the variable is assigned to None, skip to add the variable to the integer. If the variable does not have a value, you can not add it. If the variable type is NoneType, avoid adding the variable to the integer. Otherwise, the output will be unpredictable. If a variable is None, use an alternate flow in the code.
x = None
y = 2
if x is not None :
print x + y
else :
print y
Output
2
[Finished in 0.1s]
Solution 3
If the variable is assigned to None, assign the default value to the variable. For eg, if the variable is None, assign the variable to 0. The error will be thrown if the default value is assigned to it. The variable that is None has no meaning at all. You may assign a default value that does not change the value of the expression. In addition, the default value is set to 0. In the case of multiplication, the default value is 1.
x = None
y = 2
if x is None :
x = 0
print x + y
Output
2
[Finished in 0.1s]
I don’t understand this error OR what it means. I will paste my code underneath, but I don’t think it is really relevant; I just want to understand this error.
It’s just a bit of code to add up the letters in all numbers 1 — 1000 (inclusive)
def number_translator(x):
if x == 1:
return 3
elif x == 2:
return 3
elif x == 3:
return 5
elif x == 4:
return 4
elif x == 5:
return 4
elif x == 6:
return 3
elif x == 7:
return 5
elif x == 8:
return 5
elif x == 9:
return 4
elif x == 10:
return 3
elif x == 11:
return 6
elif x == 12:
return 6
elif x == 14:
return 8
elif x == 15:
return 7
elif x == 16:
return 7
elif x == 17:
return 9
elif x == 18:
return 8
elif x == 19:
return 8
elif x == 20:
return 6
elif x == 30:
return 6
elif x == 40:
return 5
elif x == 50:
return 5
elif x == 60:
return 5
elif x == 70:
return 7
elif x == 80:
return 6
elif x == 90:
return 6
count = 0
for element in range(1, 1001):
if element < 21:
count += number_translator(element) # for numbers 1 - 20
elif 20 < element < 100:
count += number_translator(int(str(element)[0]) * 10) + number_translator(int(str(element)[1])) # for numbers 21 through 100
elif element % 100 == 0 and element != 1000:
count += number_translator(int(str(element)[0])) + 7 # for numbers divisible by 100, but not 1000
elif element == 1000:
count += 11 # just for 1000
elif element % 100 < 20:
count += number_translator(int(str(element)[0])) + 10 + number_translator(int(str(element)[1:3])) # now I add in numbers like 101 - 120, 201 - 220, etc.
else:
count += number_translator(int(str(element)[0])) + 10 + number_translator(int(str(element)[1]) * 10) + number_translator(int(str(element)[2])) # now the rest( 121, 122, 123, 225, 256, 984, etc.)
print(count)
- the
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'in Python - Fix the
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'in Python - Fix the
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'Inside a Function

In Python the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' occurs when you add an integer value with a null value. We’ll discuss in this article the Python error and how to resolve it.
the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python
The Python compiler throws the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' because we are manipulating two values with different datatypes. In this case, the data types of these values are int and null, and the error is educating you that the operation is not supported because the operand int and null for the + operator are invalid.
Code Example:
a = None
b = 32
print("The data type of a is ", type(a))
print("The data type of b is ", type(b))
# TypeError --> unsupported operand type(s) for +: 'NoneType' and 'int'
result = a+b
Output:
The data type of a is <class 'NoneType'>
The data type of b is <class 'int'>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
As we see in the output of the above program, the data type of a is NoneType, whereas the data type of b is int. When we try to add the variables a and b, we encounter the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'.
Here are a few similar cases that also cause TypeError because their data types differ.
# Adding a string and an integer
a = "string"
b = 32
a+b # --> Error
# Adding a Null value and a string
a = None
b = "string"
a+b # --> Error
# Adding char value and a float
a = 'D'
b = 1.1
a+b # --> Error
Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python
You cannot use null to perform arithmetic operations on it, and the above program has demonstrated that it throws an error. Furthermore, if you have any similar case, you typecast the values before performing any arithmetic operations or other desired tasks.
To fix this error, you can use valid data types to perform any arithmetic operations on it, typecast the values, or if your function returns null values, you can use try-catch blocks to save your program from crashing.
Code Example:
a = "Delf"
b = "Stack"
print("The data type of a is ", type(a))
print("The data type of b is ", type(b))
result = a+b
print(result)
Output:
The data type of a is <class 'str'>
The data type of b is <class 'str'>
DelfStack
As you can see, we have similar data types for a and b, which are perfectly concatenated without throwing any error because the nature of both variables is the same.
Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' Inside a Function
Code Example:
def sum_ab(a, b=None):
return a+b #TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
sum_ab(3)
Output:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
In the above code, the sum_ab() function has two arguments, a and b, whereas b is assigned to a null value its the default argument, and the function returns the sum of a and b.
Let’s say you have provided only one parameter, sum_ab(3). The function will automatically trigger the default parameter to None, which cannot be added, as seen in the above examples.
In this case, if you are unsure what function raised the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int', you can use the try-catch mechanism to overcome such errors.
Code Example:
try:
def sum_ab(a, b=None):
return a+b
sum_ab(3)
except TypeError:
print(" unsupported operand type(s) for +: 'int' and 'NoneType' n The data types are a and b are invalid")
Output:
unsupported operand type(s) for +: 'int' and 'NoneType'
The data types are a and b are invalid
The try-catch block helps you interpret the errors and protect your program from crashing.
|
misterJ 0 / 0 / 0 Регистрация: 03.12.2020 Сообщений: 3 |
||||
|
1 |
||||
|
03.12.2020, 19:09. Показов 10493. Ответов 4 Метки нет (Все метки)
return F(n — 1) + n Как исправить ошибку? Аналогичный код, написанный на Паскале выводит правильный ответ 9
__________________
0 |
|
Автоматизируй это!
6430 / 4129 / 1133 Регистрация: 30.03.2015 Сообщений: 12,214 Записей в блоге: 29 |
|
|
03.12.2020, 19:26 |
2 |
|
Как исправить ошибку? подумать. да, да помню, сейчас все разжую
def F(n): а если n меньше или равно 2? верно, пайтон вернет None
return F(n — 1) + n здесь вернулся NOne и ты к нему прибавляешь n Как исправить — или кидать в функцию только больше 2 или написать там и условие что вернуть если меньше или равно 2
0 |
|
299 / 181 / 95 Регистрация: 01.05.2014 Сообщений: 501 |
|
|
03.12.2020, 19:28 |
3 |
|
Аналогичный код, написанный на Паскале выводит правильный ответ 9 Хотелось бы взглянуть
0 |
|
misterJ 0 / 0 / 0 Регистрация: 03.12.2020 Сообщений: 3 |
||||
|
03.12.2020, 19:33 [ТС] |
4 |
|||
Вот код на Паскале вроде работает, выдает 9 Добавлено через 1 минуту
0 |
|
Val Rubis 299 / 181 / 95 Регистрация: 01.05.2014 Сообщений: 501 |
||||||||
|
04.12.2020, 16:00 |
5 |
|||||||
|
РешениеТак как
возвращает None, добавил
Тогда стало считать.
0 |
hi there
I am new to eras, and learning about it, for my fist model I am trying create a CNN 1D and every time I try to compile this I am getting the same error I try with even and Odds parameters,
here is the errors and bellow is the source code of my model. could some one please point me out my error and some resource for the solution?
thanks a lot
angelo
Traceback (most recent call last):
File «character_cnn.py», line 206, in
model.add(Dense(hidden_dims))
File «/usr/local/lib/python2.7/dist-packages/keras/layers/containers.py», line 32, in add
self.layers[-1].set_previous(self.layers[-2])
File «/usr/local/lib/python2.7/dist-packages/keras/layers/core.py», line 34, in set_previous
assert self.input_ndim == len(layer.output_shape), «Incompatible shapes: layer expected input with ndim=» +
File «/usr/local/lib/python2.7/dist-packages/keras/layers/core.py», line 588, in output_shape
return (input_shape[0], np.prod(input_shape[1:]))
File «/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py», line 2481, in prod
out=out, keepdims=keepdims)
File «/usr/local/lib/python2.7/dist-packages/numpy/core/_methods.py», line 35, in _prod
return umr_prod(a, axis, dtype, out, keepdims)
TypeError: unsupported operand type(s) for *: ‘NoneType’ and ‘int’
nb_samples = X_train.shape[0]
nb_features = X_train.shape[1]
newshape = (nb_samples, 1, nb_features, 1)
X_train = np.reshape(X_train, newshape).astype(np.int)
We set some hyperparameters
BATCH_SIZE = 16
maxlen = 10
max_features = a.shape[1]
FIELD_SIZE = 5 * 300
STRIDE = 300
N_FILTERS = a.shape[1]
nb_classes =22
embedding_dims = 50
nb_filters = 250
filter_length = 2
number of hidden nodes in full connected layer
hidden_dims = 250
print(‘Build model…’)
model = Sequential()
model.add(Embedding(max_features, embedding_dims))
model.add(Dropout(0.25))
print «embedding dims: «, embedding_dims
we add a Convolution1D, which will learn nb_filter
word group filters of size filter_length:
model.add(Convolution1D(input_dim=embedding_dims,
nb_filter=nb_filters,
filter_length=filter_length,
border_mode=»valid»,
activation=»relu»,
subsample_length=1))
model.add(Activation(‘relu’))
we use standard max pooling (halving the output of the previous layer):
model.add(MaxPooling1D(pool_length=2))
We flatten the output of the conv layer,
so that we can add a vanilla dense layer:
model.add(Flatten())
Computing the output shape of a conv layer can be tricky;
for a good tutorial, see: http://cs231n.github.io/convolutional-networks/
output_size = nb_filters * (((maxlen — filter_length) / 1) + 1) / 2
print output_size
print nb_filters
I get the error in here no matter any parameter that I change
model.add(Dense(hidden_dims))
model.add(Dropout(0.25))
model.add(Activation(‘relu’))
model.add(Dense(nb_classes))
We project onto a single unit output layer, and squash it with a sigmoid:
model.add(Activation(‘softmax’))
model.compile(loss=’categorical_crossentropy’,
optimizer=’adadelta’)
print «fitting model»
model.fit(X_train, y_train, batch_size=BATCH_SIZE, verbose=1,
nb_epoch=10, show_accuracy=True,
validation_split=0.1)
score = model.evaluate(X_test, Y_test, show_accuracy=True, verbose=0)
print(‘Test score:’, score[0])
print(‘Test accuracy:’, score[1])
Python provides support for arithmetic operations between numerical values with arithmetic operators. Suppose we try to perform certain operations between a string and an integer value, for example, concatenation +. In that case, we will raise the error: “TypeError: unsupported operand type(s) for +: ‘str’ and ‘int’”.
This tutorial will go through the error with example scenarios to learn how to solve it.
Table of contents
- TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
- What is a TypeError?
- Artithmetic Operators
- Example: Using input() Without Converting to Integer Using int()
- Solution
- Variations of TypeError: unsupported operand type(s) for: ‘int’ and ‘str’
- TypeError: unsupported operand type(s) for -: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for %: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for ** or pow(): ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for //: ‘int’ and ‘str’
- Solution
- TypeError: unsupported operand type(s) for -: ‘int’ and ‘str’
- Summary
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
What is a TypeError?
TypeError tells us that we are trying to perform an illegal operation for a specific Python data type. TypeError exceptions may occur while performing operations between two incompatible data types. In this article, the incompatible data types are string and integer.
Artithmetic Operators
We can use arithmetic operators for mathematical operations. There are seven arithmetic operators in Python:
| Operator | Symbol | Syntax |
|---|---|---|
| Addition | + | x + y |
| Subtraction | – | x -y |
| Multiplication | * | x *y |
| Division | / | x / y |
| Modulus | % | x % y |
| Exponentiation | ** | x ** y |
| Floor division | // | x // y |
All of the operators are suitable for integer operands. We can use the multiplication operator with string and integer combined. For example, we can duplicate a string by multiplying a string by an integer. Let’s look at an example of multiplying a word by four.
string = "research" integer = 4 print(string * integer)
researchresearchresearchresearch
Python supports multiplication between a string and an integer. However, if you try to multiply a string by a float you will raise the error: TypeError: can’t multiply sequence by non-int of type ‘float’.
However, suppose we try to use other operators between a string and an integer. Operand x is a string, and operand y is an integer. In that case, we will raise the error: TypeError: unsupported operand type(s) for: [operator]: ‘str’ and ‘int’, where [operator] is the arithmetic operator used to raise the error. If operand x is an integer and operand y is a string, we will raise the error: TypeError: unsupported operand type(s) for: [operator]: ‘int’ and ‘str’. Let’s look at an example scenario.
Example: Using input() Without Converting to Integer Using int()
Python developers encounter a common scenario when the code takes an integer value using the input() function but forget to convert it to integer datatype. Let’s write a program that calculates how many apples are in stock after a farmer drops off some at a market. The program defines the current number of apples; then, the user inputs the number of apples to drop off. We will then sum up the current number with the farmer’s apples to get the total apples and print the result to the console. Let’s look at the code:
num_apples = 100
farmer_apples = input("How many apples are you dropping off today?: ")
total_apples = num_apples + farmer_apples
print(f'total number of apples: {total_apples}')
Let’s run the code to see what happens:
How many apples are you dropping off today?: 50 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) 1 total_apples = num_apples + farmer_apples TypeError: unsupported operand type(s) for +: 'int' and 'str'
We raise the because Python does not support the addition operator between string and integer data types.
Solution
The solve this problem, we need to convert the value assigned to the farmer_apples variable to an integer. We can do this using the Python int() function. Let’s look at the revised code:
num_apples = 100
farmer_apples = int(input("How many apples are you dropping off today?: "))
total_apples = num_apples + farmer_apples
print(f'total number of apples: {total_apples}')
Let’s run the code to get the correct result:
How many apples are you dropping off today?: 50 total number of apples: 150
Variations of TypeError: unsupported operand type(s) for: ‘int’ and ‘str’
If we are trying to perform mathematical operations between operands and one of the operands is a string, we need to convert the string to an integer. This solution is necessary for the operators: addition, subtraction, division, modulo, exponentiation and floor division, but not multiplication. Let’s look at the variations of the TypeError for the different operators.
TypeError: unsupported operand type(s) for -: ‘int’ and ‘str’
The subtraction operator – subtracts two operands, x and y. Let’s look at an example with an integer and a string:
x = 100
y = "10"
print(f'x - y = {x - y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x - y = {x - y}')
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x - y = {x - int(y)}')
x - y = 90
TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’
The division operator divides the first operand by the second and returns the value as a float. Let’s look at an example with an integer and a string :
x = 100
y = "10"
print(f'x / y = {x / y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x / y = {x / y}')
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x / y = {x / int(y)}')
x / y = 10.0
TypeError: unsupported operand type(s) for %: ‘int’ and ‘str’
The modulus operator returns the remainder when we divide the first operand by the second. If the modulus is zero, then the second operand is a factor of the first operand. Let’s look at an example with an and a string.
x = 100
y = "10"
print(f'x % y = {x % y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x % y = {x % y}')
TypeError: unsupported operand type(s) for %: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x % y = {x % int(y)}')
x % y = 0
TypeError: unsupported operand type(s) for ** or pow(): ‘int’ and ‘str’
The exponentiation operator raises the first operand to the power of the second operand. We can use this operator to calculate a number’s square root and to square a number. Let’s look at an example with an integer and a string:
x = 100
y = "10"
print(f'x ** y = {x ** y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x ** y = {x ** y}')
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x ** y = {x ** int(y)}')
x ** y = 100000000000000000000
TypeError: unsupported operand type(s) for //: ‘int’ and ‘str’
The floor division operator divides the first operand by the second and rounds down the result to the nearest integer. Let’s look at an example with an integer and a string:
x = 100
y = "10"
print(f'x // y = {x // y}')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 print(f'x // y = {x // y}')
TypeError: unsupported operand type(s) for //: 'int' and 'str'
Solution
We must convert the y variable to an integer using the int() function to solve this. Let’s look at the revised code and result:
x = 100
y = "10"
print(f'x // y = {x // int(y)}')
x // y = 10
Summary
Congratulations on reading to the end of this tutorial! The error: TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ occurs when we try to perform addition between an integer value and a string value. Python does not support arithmetic operations between strings and integers, excluding multiplication. To solve this error, ensure you use only integers for mathematical operations by converting string variables with the int() function. If you want to concatenate an integer to a string separate from mathematical operations, you can convert the integer to a string. There are other ways to concatenate an integer to a string, which you can learn in the article: “Python TypeError: can only concatenate str (not “int”) to str Solution“. Now you are ready to use the arithmetic operators in Python like a pro!
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
Integer values cannot be subtracted from string values and vice versa. This is because strings and integers are separate data types. If you try to subtract a string from an integer, you receive an error like “TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’”.
In this guide, we talk about the significance of this error and why it is raised. We walk through an example to help you figure out how to solve this error in your code.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’
Unlike other programming languages, Python syntax is strongly typed. One consequence of this is you have to change the types of objects, like strings and integers, if you want to treat them as a different type of data.
When you try to subtract a string for an integer or vice versa, Python does not know what to do. This is because you cannot subtract string values.
Similarly, you cannot add a string to an integer or divide a string by an integer. These operations all return an “unsupported operand type(s)” error.
An Example Scenario
We’re going to build a spending application that tracks how much money someone will have left on their budget after making a purchase. This application asks a user to insert the value of each purchase they make. This will be subtracted from the total amount a user has in their budget.
To start, ask a user to set a budget using the input() method:
budget = int(input("What is your budget for this month? "))
We have converted this value to an integer using the int() method. Next, we ask a user to provide some details about their purchase. We ask about what they purchased and how much their purchase cost:
purchase = input("What did you purchase? ")
price = input("How much was this purchase? ")
Next, we subtract the value of “price” from “budget”. This tells us how much a user has left in their budget.
We do this using the subtraction operator (-):
money_left = budget - price
print("You have ${} left in your budget.".format(money_left))
Run our code to see if our program works:
What is your budget for this month? 400 What did you purchase? Monitor stand How much was this purchase? 35 Traceback (most recent call last): File "main.py", line 5, in <module> money_left = budget - price TypeError: unsupported operand type(s) for -: 'int' and 'str'
We’ve told our program our budget is $400 for the month. We have just purchased a monitor stand that cost $35. Our program fails to calculate our new budget. Let’s fix this error.
The Solution
To solve this error, we convert the value of “price” to a string.
By default, input() returns a string. We changed the value of “budget” to be an integer earlier in our code. However, we did not change the value of “price”. This results in our code subtracting an integer from a string which is not possible.
Python cannot automatically convert a string to an integer because Python is statically typed.
We solve this error by replacing the “price” declaration with this code:
price = int(input("How much was this purchase? "))
We have surrounded the input() statement with int(). This makes the value stored in the “price” variable an integer. This converts the value a user inserts into our program to an integer. Run our code with this revised line of code:
What is your budget for this month? 400 What did you purchase? Monitor stand How much was this purchase? 35 You have $365 left in your budget.
Our code runs successfully. Our code subtracts 35 from 400. Our program then prints out how much money we have left in our budget to the console.
Similar Errors
There are a number of “unsupported operand type(s)” errors in Python.
These errors mean the same thing: you are trying to perform a mathematical operation on a string and a numerical value. Because strings do not support mathematical operations, you’ll encounter an error.
For instance, you see this error if you try to add a string and an integer:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Similarly, you see this error if you try to find the remainder of a string and an integer:
TypeError: unsupported operand type(s) for %: 'int' and 'str'
To solve this error in all cases, make sure you convert any string values to an integer before you use them in your code. You can do this using the int() method.
Conclusion
The “TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’” error is raised when you try to subtract a string from an integer.
You solve this error by converting all strings to integers using the int() method before performing a mathematical operation.
Now you’re ready to solve this common Python error like a professional developer!

Сообщение было отмечено misterJ как решение