d = {1: 1}
def nterms(n):
if n in d: return d[n]
else:
if n%2: d[n] = 1+nterms(3*n+1)
else: d[n] = 1+nterms(n/2)
print (max((nterms(n),n) for n in range(2,10**6)))
Выдаёт ошибку “Traceback (most recent call last)” и далее следует “TypeError: unsupported operand type(s) for +: ‘int’ and ‘NoneType'”, как я понял происходит слишком много вызовов.
Как можно исправить эту ошибку?
Kromster
13.5k12 золотых знаков43 серебряных знака72 бронзовых знака
задан 11 фев 2022 в 16:04
Из функции всегда нужно что-то возвращать, если вы потом используете её результат. У вас в ветке else:
ничего не возвращается (а значит, возвращается None
с точки зрения питона). Если я правильно понимаю, вам везде нужно возвращать d[n]
, поэтому, чтобы не писать одинаковые return
-ы во всех ветках, проще инвертировать условие и сначала посчитать d[n]
, если оно ещё не посчитано, а потом вернуть его в любом случае:
def nterms(n):
if n not in d:
if n%2:
d[n] = 1+nterms(3*n+1)
else:
d[n] = 1+nterms(n/2)
return d[n]
Теперь функция всегда возвращает d[n]
, при любом n
.
ответ дан 11 фев 2022 в 16:23
CrazyElfCrazyElf
65.4k5 золотых знаков19 серебряных знаков50 бронзовых знаков
0
Как исправить: TypeError: неподдерживаемые типы операндов для -: 'str' и 'int'
17 авг. 2022 г.
читать 1 мин
Одна ошибка, с которой вы можете столкнуться при использовании Python:
TypeError : unsupported operand type(s) for -: 'str' and 'int'
Эта ошибка возникает при попытке выполнить вычитание со строковой переменной и числовой переменной.
В следующем примере показано, как устранить эту ошибку на практике.
Как воспроизвести ошибку
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'points_for': ['18', '22', '19', '14', '14', '11', '20', '28'],
'points_against': [5, 7, 17, 22, 12, 9, 9, 4]})
#view DataFrame
print(df)
team points_for points_against
0 A 18 5
1 B 22 7
2 C 19 17
3 D 14 22
4 E 14 12
5 F 11 9
6 G 20 9
7 H 28 4
#view data type of each column
print(df.dtypes )
team object
points_for object
points_against int64
dtype: object
Теперь предположим, что мы пытаемся вычесть столбец points_against из столбца points_for :
#attempt to perform subtraction
df['diff'] = df.points_for - df.points_against
TypeError : unsupported operand type(s) for -: 'str' and 'int'
Мы получаем TypeError , потому что столбец points_for является строкой, а столбец points_against — числовым.
Для выполнения вычитания оба столбца должны быть числовыми.
Как исправить ошибку
Чтобы устранить эту ошибку, мы можем использовать .astype(int) для преобразования столбца points_for в целое число перед выполнением вычитания:
#convert points_for column to integer
df['points_for'] = df['points_for'].astype (int)
#perform subtraction
df['diff'] = df.points_for - df.points_against
#view updated DataFrame
print(df)
team points_for points_against diff
0 A 18 5 13
1 B 22 7 15
2 C 19 17 2
3 D 14 22 -8
4 E 14 12 2
5 F 11 9 2
6 G 20 9 11
7 H 28 4 24
#view data type of each column
print(df.dtypes )
team object
points_for int32
points_against int64
diff int64
dtype: object
Обратите внимание, что мы не получаем ошибку, потому что оба столбца, которые мы использовали для вычитания, являются числовыми столбцами.
Дополнительные ресурсы
В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:
Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами
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!
А вот и полный код
what = input( "Что делаем? (+,-):" )
a = input("Введи первое число: ")
b = input("Введи второе число: ")
if what == "+":
c = a + b
print("Результат: " + c)
elif what == "-":
c = a - b
print("Результат: " + c)
else:
print("Выбрана неверная операция!")
-
Вопрос задан21 мар.
-
159 просмотров
Пригласить эксперта
Функция input
по стандарту возвращает строку (объект типа str
). Невозможно вычесть строку из строки (для двух объектов типа str
не определен метод __sub__
). Нужно явно привести a
и b
к целым числам (int
) или числам с плавающей точкой (float
). Объекты этого типа можно вычитать друг из друга.
a = int(input())
b = int(input())
a = int(input("Введи первое число: "))
b = int(input("Введи второе число: "))
-
Показать ещё
Загружается…
15 мая 2023, в 00:10
2000 руб./за проект
15 мая 2023, в 00:07
500 руб./за проект
14 мая 2023, в 22:02
20000 руб./за проект
Минуточку внимания
Whether you are a newbie or an experienced programmer, you will occasionally encounter the “TypeError: unsupported operand type(s) for -: str and int” error when working with Python. If you are struggling with it, then continue reading the guide below to understand them.
Causes of the “TypeError: unsupported operand type(s) for -: str and int” error
This error occurs when you try to perform mathematical operations (addition, subtraction, multiplication, division) between a number and a string. Take a look at the code below to understand it better.
balance = 1000 withdrawal = input("How much are you withdrawing today? ") balance = balance - withdrawal print(f"Your balance: {balance}")
Output:
How much are you withdrawing today? 34.5
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Two easy ways to fix this problem
Basically, you just don’t attempt to subtract between a string and an integer, and you can avoid this error.
Here are two straightforward ways to fix it:
Using int() function
Syntax:
int(value, base)
Parameters:
value
: A number that isn’t an int or a string.base
: The number format. Default: base = 10.
In the above example, the input()
function returns the entered data in string format. We will get an error when we take that input data and do a subtraction between string and an int.
The problem will be solved by converting the return value of the input()
to an int value using the int()
function. Like this:
balance = 1000 withdrawal = int(input("How much are you withdrawing today? ")) balance = balance - withdrawal print(f"Your balance: {balance}")
Output:
How much are you withdrawing today? 50
Your balance: 950
Using float() function
Syntax:
float(value)
Parameter:
value
: A number or a string that you want to convert to a floating point number.
We can solve the problem by replacing float()
for int()
in the example above. But the value returned between int()
and float()
is a different numeric type. So, depending on each case, choose to use float or int properly.
balance = 1000 withdrawal = float(input("How much are you withdrawing today? ")) balance = balance - withdrawal print(f"Your balance: {balance}")
Output:
How much are you withdrawing today? 50.0
Your balance: 950.0
Summary
The “TypeError: unsupported operand type(s) for -: str and int” error in Python is a problem that is very easy to fix. You just need to understand the data type of each variable in your entire program. Hope this article is helpful to you. Thanks for reading!
Maybe you are interested:
- UnicodeDecodeError: ‘ascii’ codec can’t decode byte
- TypeError: Object of type DataFrame is not JSON serializable in Python
- TypeError: ‘dict’ object is not callable in Python
- TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’
- TypeError: ‘str’ object cannot be interpreted as an integer
Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java