python - Collat​​z 序列 - 最后得到 None

标签 python python-3.x math nonetype collatz

从 Al Sweigart 的“自动化无聊的东西”中学习。第 3 章末尾给出了 Collat​​z 数列作为练习。输出似乎是正确的,但最后一行中有一个“无”。在下面的代码中,我猜测当 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 - Collat​​z 序列 - 最后得到 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151787/

相关文章:

python - 从 Simulink 模型获取模型拓扑

python 在后台触发并忘记异步函数

algorithm - 在完整图的有序集中查找顶点

math - 3D旋转矩阵(旋转到另一个引用系)

python - 为什么我的 Python 程序在 IDE(pycharm) 中运行,但当我从命令行尝试时却没有?

c# - 按百分比递增、递减

python - 如何在没有标题的情况下读取 ".dat file"中的特定列,然后将其存储在列表中以转换赤经和赤纬

python - 重构函数定义

python - 将十六进制字符串转换为 bytes 函数的正确形式

python - 计算列表项并存储在列表项对应的数据框列中