【问题标题】:Python TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'Python 类型错误:/ 不支持的操作数类型:\'NoneType\' 和 \'int\'
【发布时间】:2023-02-12 07:07:44
【问题描述】:

我有一个列表,其中只有一个值,填充在一个函数中。 我有另一个函数,我想获取该值,将其除以 2,然后将其放入另一个列表中。

我发现了类似的问题,但似乎没有一个与我的问题完全相同,而且修复似乎对我的问题不起作用。

from random import randint
import random

finalList = [None] * 100
firstList = [None] * 30
secondList = []

def funcOne():
    global firstList
    
    for b in range(1):
        firstList.append(random.randrange(11,12,1))

    return firstList


def funcTwo():
    global finalList

    finalList[0] = firstList
    for i in firstList:
        secondList.append(i/2)
    finalList[1] = 5 + secondList

    return finalList
    print(finalList)

funcOne()
funcTwo()

我收到: 发生异常:TypeError / 不支持的操作数类型:“NoneType”和“int” 文件“C:\Users\redy\OneDrive\Documents\RPG\Biographies\TLoE_Codes\from random import randint.py”,第 22 行,在 funcTwo 中 secondList.append(i/2) 文件“C:\Users\redy\OneDrive\Documents\RPG\Biographies\TLoE_Codes\from random import randint.py”,第 29 行,在 函数二() TypeError: 不支持的操作数类型 /: 'NoneType' 和 'int'

【问题讨论】:

  • for b in range(1) 的目的是什么?

标签: python nonetype operands


【解决方案1】:

在迭代期间,您分配了i = None, 然后尝试计算表达式 None / 2。 不要那样做,因为它不会工作,它会给出你报告的 TypeError。

更喜欢将数字数量分配给i,并且然后除以 2。

【讨论】:

    【解决方案2】:

    您附加到 firstList,一个以 100 Nones 开头的列表。前 100 个元素将产生 None/2。将其初始化为firstList = []

    另外,您认为for b in range(1): 是做什么的?

    【讨论】:

      猜你喜欢
      • 2014-03-16
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      相关资源
      最近更新 更多