Collat​​z序列-最后得到一个None

时间:2019-03-13 21:55:49

标签: python python-3.x math nonetype collatz

从Al Sweigart的“自动完成无聊的事情”中学习。在第3章的末尾,按惯例给出了Collat​​z序列。输出似乎正确,但是最后一行有一个“ None”。在下面的代码中,我猜想当p = 1时,它退出了while循环,因此没有任何可打印的内容,因此它给出了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

1 个答案:

答案 0 :(得分:0)

正如注释中已经指出的那样,您的函数返回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')

随时提出任何问题或以可能错误的假设纠正我! :)