Unsupported operand type s for int and nonetype как исправить

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's user avatar

Kromster

13.5k12 золотых знаков43 серебряных знака72 бронзовых знака

задан 11 фев 2022 в 16:04

RezDom's user avatar

Из функции всегда нужно что-то возвращать, если вы потом используете её результат. У вас в ветке 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

CrazyElf's user avatar

CrazyElfCrazyElf

65.4k5 золотых знаков19 серебряных знаков50 бронзовых знаков

0

artemu88

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))

Код твой не правила, просто добавила else, чтобы программа корректно завершалась

Отредактировано Ocean (Июль 12, 2021 14:39:16)

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]
  1. the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python
  2. Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in Python
  3. Fix the TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' Inside a Function

Python TypeError: Unsupported Operand Type(s) for +: 'NoneType' and 'Int'

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.

Answer by Claire Madden

Thanks for contributing an answer to Stack Overflow!,Whenever you see an error that include ‘NoneType’ that means that you have an operand or an object that is None when you were expecting something else.,Please be sure to answer the question. Provide details and share your research!,Asking for help, clarification, or responding to other answers.

In your giant elif chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:

...
elif x == 90:
    return 6
else:
    raise ValueError(x)

Answer by Barrett Scott

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.,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.,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.,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.

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]

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]

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]

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]

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]

Answer by Adalyn Parra

Values equal to None cannot be concatenated with a string value. This causes the error “TypeError: unsupported operand type(s) for +: ‘nonetype’ and ‘str’”.,The “TypeError: unsupported operand type(s) for +: ‘nonetype’ and ‘str’” error is raised when you try to concatenate a value equal to None with a string. This is common if you try to concatenate strings outside of a print() statement.,Python TypeError: unsupported operand type(s) for +: ‘nonetype’ and ‘str’ Solution,Strings can be concatenated in Python. This lets you merge the value of two or more strings into one string. If you try to concatenate a string and a value equal to None, you’ll encounter the “TypeError: unsupported operand type(s) for +: ‘nonetype’ and ‘str’” error.

day = "Monday"
weather = "sunny"
print("It's " + day + " and it is " weather + " outside.")

Answer by Raiden Nixon

Traceback (most recent call last):
File “python”, line 7, in
File “python”, line 6, in factorial
TypeError: unsupported operand type(s) for *: ‘int’ and ‘NoneType’,def factorial(x):
total = 0
if x == 1 or x == 0:
return 1
else:
total = x * factorial(x-1)
print factorial(3),<What do you expect to happen instead?>
But i want to know does it really work by giving parameters
And i got this error:,There are several ways to correct this. This one omits the total variable, since it is not needed …

<In what way does your code behave incorrectly? Include ALL error messages.>
I do this exercise with this code (and its works):

def factorial(x):
    total = 0
    if x == 1 or x == 0:
        return 1
    else:
        total = x * factorial(x - 1)
        return total

def factorial(x):
total = 0
if x == 1 or x == 0:
return 1
else:
total = x * factorial(x-1)
print factorial(3)

<do not remove the three backticks above>

Answer by Avianna Watkins

Hi guys i have below code . trying to separate number,alphabet,alphanumeric from the string,Could you suggest why i getting this error as i am sure that ‘i’ is of string type,

I am trying to calculate numerical integration …READ MORE,i am getting the below error for this code :

Hi guys i have below code . trying to separate number,alphabet,alphanumeric from the string

import re

test_str = " Delivery Centre Strategy & Operations  - 17762-DCSO"

 

def manipulate(test_str):

    label = test_str.lstrip()

    number =''

    albhabet=''

    res = re.split(r'[-_&s]s*', label)

    print(res)

    while("" in res):

        res.remove("")

    print(res)

    for i in res:

        i=i.lstrip()

        print("i ->", type(i),i )

        if i.isalpha():

            albhabet +=i

            albhabet +=' '

        elif i.isdigit():

            print(type(i))

            number = number + i

            print(type(number))

        elif i.isalnum:

            al=''

            nu=''

            for k in range(0,len(i)):

                if i[k].isdigit():

                    nu +=i[k]

                elif i[k].isalpha():

                    al +=i[k]

            number +=nu

            albhabet +=al

            albhabet +=" "

      if not number:

            number = None

    return number,albhabet

result = manipulate(test_str)

app_name = result[1]

ARI = result[0]

print (ARI,app_name)

i am getting the below error for this code :

number = number + i
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

Answer by Josie Franco

cr.execute(‘update ‘+self._table+’ set parent_left=%s,parent_right=%s where id=%s’, (pleft+1, pleft+2, id_new)),TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’,I have resolved this issue after waste lot of time.
I found two fields that was blank in stock.location i.e. parent_left and parent_right.
Value of both field matter on the all operations related to inventory.
Now My existing database working fine after set the values of these fields.,Odoo is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

2. Run odoo by command: 

python odoo.py shell -d <dbname>

3. In the interactive shell run the following statements:

self.env['stock.warehouse']._parent_store_compute()       //This should return Trueself.env.cr.commit()

Answer by Bria Allen

TensorFlow installed from (source or binary): source,TensorFlow version (use command below): 2.1.0,By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.,@Flamefire Could you please provide us with simple standalone code to reproduce the issue in our environment, Thanks.

tensorflow.python.framework.errors_impl.OutOfRangeError: 2 root error(s) found.
  (0) Out of range:  End of sequence
	 [[node IteratorGetNext_2 (defined at git/tensorflow_tests/train_distributed.py:212) ]]
	 [[metrics/accuracy/div_no_nan/allreduce_1/CollectiveReduce/_70]]
  (1) Out of range:  End of sequence
	 [[node IteratorGetNext_2 (defined at git/tensorflow_tests/train_distributed.py:212) ]]

Answer by Saul Peters

As the script works for some files and not for others, I suspect the problem is originated somewhere in the data (or handling of special cases in the data). TypeError suggest that you may have a mix of data types. I’m not sure how numpy would handle a mix like that. Have you tried to e.g. float the elevation to make sure they are all float numbers? ,I recently came up with an error in a script I am working with in Python for ArcGIS 10.1. The strange thing about it is that this script works for some files and not for others.
Any ideas as to why this is happening?,If you insert a print statement as below, I suspect that you will find path has a value other than what you expect when the error is thrown. ,If it is set to something that you do expect then at least we will have narrowed down where to look for the error.

i.e.something like:

with arcpy.da.SearchCursor(path, "Elevation") as sCursor:
    for row in sCursor:
        data_elevation.append(float(row[0]))

Понравилась статья? Поделить с друзьями:
  • Как найти число вариантов в выборке
  • Как найти средневзвешенную ставку по кредитам
  • Как найти знакомых в китае
  • Как найти работу в интернете бухгалтером
  • Как составить кроссворд фото с ответами