Ошибка typeerror unsupported operand type s for int and nonetype

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)

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)

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)

Достаточно часто возникают вопросы: «почему моя функция ничего не возвращает?!», «почему из функции возвращается None?», «не могу понять откуда появляется None…».

Для начала необходимо понимать и помнить, что любая функция в Python всегда что-то возвращает и если не используется оператор return для возврата значения (такие случаи бывают, но об этом позднее), то функция возвращает объект None. В случае если return используется, но после него ничего не указывается явно, то по умолчанию считается, что там стоит объект None.

# Не используем оператор return, поэтому результат не возвращается.
def func(x):
    x * x  

print(func(10))
#=> None

# Используем оператор return, но не задаем явное значение/используем некорректно
def func(x):
    x * x
    return

print(func(10))
#=> None

# Корректно возвращаем результат с использованием оператора return
def func(x):
    return x * x

print(func(10))
#=> 100

Порой бывает, что по ошибке указывается возврат вместе с функцией print(). Для информации функция print() в Python выводит переданные аргументы на стандартное устройство вывода (экран), но при этом не возвращает значений, т.е. можно считать, что возвращает None.

def func(x):
    return print(x * x)

a = 5
b = func(a)  # Присваиваем результат функции переменной b
# Результат работы функции выводится на экран, благодаря print() в теле функции.
#=> 25
# Но при этом данный результат не присваивается переменной b.
print(b)
#=> None

Если дальше по коду проводятся манипуляции с переменной b, например сложение, то возникнет ошибка TypeError:

c = b + 1  # Пытаемся сложить None и 1
print(c)
# => TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Возможен вариант, когда функция и не должна ничего возвращать, она производит какие-либо действия с объектами в глобальной зоне видимости и на этом ее функционал заканчивается. В таком случае return может и не использоваться, но необходимо помнить, что в этом случае функция возвращает None.

# Бесполезная функция необходимая только в качестве примера.
def extend_list(list1, list2):
    list1.extend(list2)


list1 = [1, 2]
list2 = [3, 4]
print(extend_list(list1, list2))
# => None
#  При этом поставленную задачу функция выполнила - изменила list1
print(list1)
# => [1, 2, 3, 4]

В примере выше использовался метод работы со списками extend() и необходимо понимать, что метод изменяет объект, к которому применен, а не возвращает результат изменения объекта.

list3 = extend_list(list1, list2)
print(list3)
# =>  None

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

  • Ошибка typeerror numpy ndarray object is not callable
  • Ошибка traymenu exe при загрузке компа 007
  • Ошибка trapper b2fe5bad far cry 6
  • Ошибка trapper 1c07b734 far cry 5
  • Ошибка transport vmdb error 14 pipe connection has been broken