Python 循环卡住且没有错误

标签 python python-3.x

我正在尝试用 Python 编写一段代码,显示使用简单算法从任意数字达到 1 所需的步骤数。这是我的代码:

print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
    count = 0
    num = n
    while not num == 1:
        if num % 2 == 0:
            num = num / 2
        else:
            num = (num * 3) + 1
    count = count + 1
    print('Number: '+str(int(n)+min)+'   Steps needed: '+count)

它卡住了,没有显示错误消息,我不知道为什么会发生这种情况。

最佳答案

1) 您错误地调用了 range()

您的代码:for n in range(max - min): 生成从 0 开始并以值 max-min< 结束的数字范围。相反,您需要从 min 开始到 max 结束的数字范围。

试试这个:

for n in range(min, max):

2) 您正在执行浮点除法,但该程序应该仅使用整数除法。试试这个:

num = num // 2

3) 您正在错误的循环上下文中更新 count 变量。尝试将其缩进一站。

4)您的最后一行可能是:

print('Number: '+str(n)+'   Steps needed: '+str(count))

程序:

print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
    count = 0
    num = n
    while not num == 1:
        if num % 2 == 0:
            num = num // 2
        else:
            num = (num * 3) + 1
        count = count + 1
    print('Number: '+str(n)+'   Steps needed: '+str(count))

结果:

Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5

Number: 3   Steps needed: 7
Number: 4   Steps needed: 2
Number: 5   Steps needed: 5

关于Python 循环卡住且没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38468670/

相关文章:

python - 查找具有公差的重复项并分配给 Pandas 中的一个集合

Python MatPlot 条函数参数

python - 如何拆分由项目符号分隔的文件

python - 焦点事件改变了吗?

python - 读取文本文件时如何修复此 cp950 "illegal multibyte sequence"UnicodeDecodeError?

python-3.x - Gunicorn 不使用套接字与 nginx 绑定(bind)

python - 我需要比较 2 个不同数据帧的 2 个字段(如果匹配),我们需要填充详细信息,否则在 python 中填充空值

python - 获取递归错误: maximum recursion depth exceeded in comparison

python - Matplotlib 堆积条形图 : need to swap x and height

python - 如何在discord.py中重新启动循环?