python 错误需要解释

python error need explanations

我在 运行 以下程序时出现此错误,我不明白为什么:

Traceback (most recent call last):
line 18

main()   line 13, in main

nombre=condition(nombre)  
line 3, in condition
if (nombre % 2) == 1:
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

这是我的程序:

def condition(nombre):
   if (nombre % 2) == 1:
      nombre=(nombre*3)+1
   else:
      nombre=(nombre/2)


def main():
  nombre=int(input())
  print(nombre)
  while nombre!=1:
    nombre=condition(nombre)
  print(nombre)



main()

发生此错误是因为您从条件函数中 returning 值,并且在 while 的第二次迭代中!= 1 nombre 的值等于 def。试试这个来修复你的代码:

def condition(nombre):
   if (nombre % 2) == 1:
      nombre=(nombre*3)+1
   else:
      nombre=(nombre/2)
   return nombre

如果你想要那个条件 return 整数值你应该使用 // 而不是 / :

def condition(nombre):
   if (nombre % 2) == 1:
      nombre=(nombre*3)+1
   else:
      nombre=(nombre//2)
   return nombre

您正在从 condition 函数获得 NoneType,因为它没有 return 任何东西。