首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >for循环卡住且不交互(Python 3)

for循环卡住且不交互(Python 3)
EN

Stack Overflow用户
提问于 2016-09-06 16:49:20
回答 1查看 1.2K关注 0票数 0

我目前正在编写一个小脚本,旨在查找出租车车号。只有一个小问题,for循环不会增加变量x,并且会永远循环。我将粘贴以下代码的相关部分:

代码语言:javascript
复制
n = int(10)
counter = int(0)
m = int(m)
x = int(1)
y = int(n**(1/3))
cheatsheet = []

while counter in range(0,m):
    for x in range(1,y):
        if x**3 + y**3 < n:
            print('less than')
            print(x,y,n)
            continue
        elif x**3 + y**3 > n:
            print('greater than')
            y -= 1
            continue
        elif x > y:
            if n in cheatsheet:
                print('counting')
                counter = counter+1
                #checking if n occurs in the list, if so it will add 1 to the counter so that the program will know when to stop
            n = n + 1
            y = int(n**(1/3))
            x = 1
            print('break1')
            #resetting values and bumping n so that it will continue the quest to find 'em all
            break
        else:
            if x and y == 1:
                #this is an error correction for low n values, i mean really low it might be redundant by now
                n = n + 1
                y = int(n**(1/3))
                x = 1
                print('break2')
                break
            cheatsheet.append((n,x,y))        
print(cheatsheet)

这将在终端窗口中产生以下结果:image

请注意,我自己杀死了进程,但程序没有。正如您可以看出的,该脚本只是循环并打印‘小于’和x,y,n的值。

非常感谢您的帮助!

编辑:变量m由用户提供,但不包括在这段代码中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-06 17:43:05

这有一些问题,我不愿意发布函数代码,但我会指出其中的一些问题。

对于初学者:

代码语言:javascript
复制
n = int(10)

不是必需的,不是错误而是多余的。使用具有相同效果的n = 10

然后:

代码语言:javascript
复制
while counter in range(0,m):

将始终计算为Truem从来没有修改过,所以成员测试总是成功的,也许你需要重新评估你的循环。

代码语言:javascript
复制
for x in range(1,y):

这将始终为x赋值1y根据您的算术计算为2 (整数四舍五入浮点到底数,即int(2.9) -> 2),因此要么使用math.ceil,要么在y中加1。

除此之外,你总是在循环中重新分配变量名,这是令人困惑的,并可能导致意想不到的行为。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39344596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档