python错误需要解释

2024-04-25 12:41:16 发布

您现在位置:Python中文网/ 问答频道 /正文

运行以下程序时出现此错误,我不明白原因:

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

Tags: in程序mostifmaindef错误line
2条回答

发生此错误的原因是您没有从条件函数返回值,并且在while的第二次迭代中!=nombre的1值等于def。尝试以下操作修复代码:

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

如果希望该条件返回整数值,则应使用//而不是/:

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

您将从condition函数获得NoneType,因为它不返回任何内容

相关问题 更多 >

    热门问题