- TypeError: unsupported operand type(s) in «print >> . » statement
- 1 Answer 1
- Как исправить: TypeError: неподдерживаемые типы операндов для -: 'str' и 'int'
- Как воспроизвести ошибку
- Как исправить ошибку
- Дополнительные ресурсы
- Solve Python TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’
- Other cases when None causes TypeError
- Conclusion
- Take your skills to the next level ⚡️
- About
- Search
- Python-сообщество
- #1 Июль 12, 2021 13:03:24
- Ошибка unsupported operand type(s) for +: ‘int’ and ‘NoneType’
- #2 Июль 12, 2021 14:38:49
- Ошибка unsupported operand type(s) for +: ‘int’ and ‘NoneType’
TypeError: unsupported operand type(s) in «print >> . » statement
The answer to your question is included in the error message: instead of print >>sys.stderr, TEXT you must use print (TEXT, file=sys.stderr) when using Python 3.
Thanks, it works! But I wonder that why the same code can work on openwrt( linkit 7688 duo, python supported) while on python-3.6 compiler we need to modify the print() part before compiling??
1 Answer 1
print >>sys.stderr, 'waiting for a connection'
means «print the string ‘waiting for a connection’ to the file-like object sys.stderr «.
In Python 3, print becomes a function rather than a statement, and the syntax to redirect its output looks like this:
print('waiting for a connection', file=sys.stderr)
You get a TypeError (rather than, say, a SyntaxError ) in Python 3 because, now that print is a function (and therefore an object), it can be part of an expression … and since >> is an operator, the expression fragment
is interpreted as «shift the print function right by sys.stderr bits» – which is syntactically valid, but doesn’t make any sense for those objects.
If you need to write code which runs under both Python 2 and Python 3, you can import Python 3’s behaviour into Python 2:
from __future__ import print_function # works in Python 2.6 and onwards print('whatever', file=some_file)
Note that this will disable the ability to treat print as a statement, so you’ll have to update any code which uses that behaviour.
Как исправить: TypeError: неподдерживаемые типы операндов для -: 'str' и 'int'
Одна ошибка, с которой вы можете столкнуться при использовании Python:
TypeError : unsupported operand type(s) for -: 'str' and 'int'
Эта ошибка возникает при попытке выполнить вычитание со строковой переменной и числовой переменной.
В следующем примере показано, как устранить эту ошибку на практике.
Как воспроизвести ошибку
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame() #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:
Solve Python TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’
To solve this error, make sure you are not concatenating a None value with a string value. See this tutorial for more info.
In Python, the NoneType data type represents the absence of a value or a null value.
You can initiate the NoneType object using the None keyword as follows:
You can also use the None value to indicate that a function does not return a value.
Python allows you to concatenate (or merge) two or more string values into one string using the addition + operator.
But when you merge a NoneType with a string, Python will raise a TypeError. The following code:
Gives the following output:
One common situation where this TypeError can occur is when using the print() function in Python.
In Python version 2, print is a statement so you can do concatenation like this:
But in Python v3, print() is a function that returns None .
This is why concatenating outside of the parentheses results in TypeError:
To fix this issue, you need to do the concatenation inside the parentheses as shown below:
The print() function is one source of the None value in Python3, so make sure you avoid concatenating outside the parentheses.
Other cases when None causes TypeError
Another way you can have None is when your function doesn’t return any value:
The code above defines a function called get_name() that prompts the user to enter their name and stores the input in the x variable.
If the x variable is not an empty string, the function returns the value of x .
Next, the code defines the y string with the value » is your name» .
Then, it calls the get_name() function and concatenates the returned value with the y string using the + operator, and assigns the result to the z variable.
There is a potential for the code to raise a TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’ error.
When the user enters an empty string when prompted for their name, the get_name() function will return the None value. This causes the + operator to raise the error during concatenation.
To avoid the error, you can add an else statement as shown below:
Alternatively, you can store the get_name() function result to a variable first, then check if the variable equals None before trying to concatenate it.
In this version of the code, the highlighted lines check if the name variable is None before trying to concatenate it with the y string.
Both solutions above are valid to handle any None value that may appear in your code.
Conclusion
To conclude, the TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’ error occurs in Python when you try to use the + operator to concatenate a None with a string.
To avoid this error, you need to make sure that you are not trying to concatenate a None value with a string using the + operator.
You can check if a variable is None before trying to concatenate it with a string, or you can explicitly set the return statement in a function.
You can use the examples in this article to fix the error like a professional. 👍
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Python-сообщество
- Начало
- » Python для новичков
- » Ошибка unsupported operand type(s) for +: ‘int’ and ‘NoneType’
#1 Июль 12, 2021 13:03:24
Ошибка unsupported operand type(s) for +: ‘int’ and ‘NoneType’
Всем привет!
Только начинаю учить python по бесплатным курсам.
Решал задачу на рекурсию, где нужно написать функцию суммы последовательности.
Но возникает ошибка:
unsupported operand type(s) for +: ‘int’ and ‘NoneType’
Объясните, что я делаю не так?
Всем большое спасибо!
def SumSequence(n): n = int(input()) if n != 0: return n + SumSequence(n) n = int(input()) print(SumSequence(n))
#2 Июль 12, 2021 14:38:49
Ошибка unsupported operand type(s) for +: ‘int’ and ‘NoneType’
1) почему дважды n задается?
Нужно один раз это делать.
2) Имя функции не должно быть с прописной буквы. Это описано в PEP8. SumSequence- так именую классы. Функции sum_sequence.
3) TypeError: unsupported operand type(s) for +: ‘int’ and ‘NoneType’ возникает когда ты вводишь на очередном запросе 0
Условие не выполняется, значит питон не переходит к обработке строки return n + SumSequence(n) и функция возвращает None
Отсюда и возникает сложение integer с None которое выполнить нельзя. Это как складывать жаб и стулья.
Чтобы этого избежать, надо добавить ветку else, в которой определить что должна вернуть функция в случае, когда n=0
def SumSequence(n): n = int(input()) if n != 0: return n + SumSequence(n) else: return 0 n = int(input()) print(SumSequence(n))
Отредактировано Ocean (Июль 12, 2021 14:39:16)