从 Al Sweigart 的“自动化无聊的东西”中学习。第 3 章末尾给出了 Collatz 数列作为练习。输出似乎是正确的,但最后一行中有一个“无”。在下面的代码中,我猜测当 p = 1 时,它会跳出 while 循环,然后没有任何内容可打印,因此它给出 None (?)。有人可以指出为什么添加 None 的正确方向以及如何修复它吗?
请参阅下面的代码和下面的示例结果:
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)
**
结果示例:
如果我输入数字 3,我得到:
3
10
5
16
8
4
2
1
None
最佳答案
正如评论中已经指出的,您的函数返回 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')
请随意询问任何问题或纠正我可能错误的假设! :)
关于python - Collatz 序列 - 最后得到 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151787/