Python Collatz序列-最后得到一个无
学习阿尔·斯维加特的“自动化无聊的东西”。在第三章末尾,给出了Collatz序列作为实践。输出似乎正确,但最后一行中有一个“无”。在下面的代码中,我猜当p=1时,它会退出while循环,然后就没有要打印的内容了,所以它会给出一个None(?)。有人能告诉我为什么要添加None,以及如何修复它吗 请参阅下面的代码和下面的示例结果:Python Collatz序列-最后得到一个无,python,python-3.x,math,nonetype,collatz,Python,Python 3.x,Math,Nonetype,Collatz,学习阿尔·斯维加特的“自动化无聊的东西”。在第三章末尾,给出了Collatz序列作为实践。输出似乎正确,但最后一行中有一个“无”。在下面的代码中,我猜当p=1时,它会退出while循环,然后就没有要打印的内容了,所以它会给出一个None(?)。有人能告诉我为什么要添加None,以及如何修复它吗 请参阅下面的代码和下面的示例结果: def collatz (p): while p != 1: if p % 2 ==0: p = (p//2)
def collatz (p):
while p != 1:
if p % 2 ==0:
p = (p//2)
print(p)
else:
p = ((3*p) + 1)
print(p)
print ('Select a number between 1 and 10')
entry = float(input())
number = round(entry)
if number >10 or number <1:
print('Your selection must between 1 and 10. Please try again')
else:
Program = collatz(number)
print (Program)
正如注释中已经指出的,函数返回
None
。我想我应该把你的函数做成一个生成器,你可以用这种方式迭代和打印值。这有几个优点,比如使代码更加灵活和可重用:
def collatz (p):
while p != 1:
if p % 2 == 0:
p = p / 2 # You don't need the double slash here because of the if before it
else:
p = (3*p) + 1
yield p
print('Select a number between 1 and 10')
number = int(input()) # You really want int here I think and leave out the rounding
if 1 <= number <= 10: # Slightly more pythonic
for sequence_item in collatz(number):
print(sequence_item)
else:
print('Your selection must between 1 and 10. Please try again')
def collatz(p):
而p!=1:
如果p%2==0:
p=p/2#这里不需要双斜杠,因为前面有if
其他:
p=(3*p)+1
产量p
打印('选择一个介于1和10'之间的数字)
number=int(input())35;我想你真的想要int,不需要四舍五入
如果1,则函数不显式返回任何内容。任何此类函数都隐式返回None
。您正在打印collatz()
的返回值,即None.
。函数本身打印信息,所以不需要打印结果。明白了!谢谢,谢谢。这很有帮助。我使用float的原因是,如果有人键入5.5,那么如果使用int,我会得到一个错误。因此,您希望转换输入,然后对其进行四舍五入,这样无论用户键入什么数字类型,都不会出现错误。@Philomath如果您认为它有用,您介意给我一个向上投票吗?:)已经有了。上面写着“谢谢你的反馈!声誉低于15的人所投的票将被记录,但不会改变公开显示的帖子分数
def collatz (p):
while p != 1:
if p % 2 == 0:
p = p / 2 # You don't need the double slash here because of the if before it
else:
p = (3*p) + 1
yield p
print('Select a number between 1 and 10')
number = int(input()) # You really want int here I think and leave out the rounding
if 1 <= number <= 10: # Slightly more pythonic
for sequence_item in collatz(number):
print(sequence_item)
else:
print('Your selection must between 1 and 10. Please try again')