Collatz 序列 - 最后得到 None
Collatz Sequence - getting a None at the end
向 Al Sweigart 的 "Automate The Boring Stuff" 学习。在第 3 章的末尾,给出了 Collatz 序列作为练习。输出似乎是正确的,但最后一行中有一个 'None'。在下面的代码中,我猜测当 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
正如评论中已经指出的那样,您的函数 returns 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')
请随时提出任何问题或纠正我可能错误的假设! :)
向 Al Sweigart 的 "Automate The Boring Stuff" 学习。在第 3 章的末尾,给出了 Collatz 序列作为练习。输出似乎是正确的,但最后一行中有一个 'None'。在下面的代码中,我猜测当 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
正如评论中已经指出的那样,您的函数 returns 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')
请随时提出任何问题或纠正我可能错误的假设! :)