这个问题在这里已有答案:
学习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')
随意提出任何问题或在可能错误的假设下纠正我! :)