Python 3无法循环中断

时间:2017-09-07 04:41:34

标签: python python-3.x

我是编码的新手,有一个简单的问题,我不明白如何修复。我正在玩我目前在Python中学到的东西。第二个代码“print(”Breaking!“)和break中的循环不会破坏while循环i + = 1.我该如何解决这个问题?

i=0
while True:
i+=1
if i==10000:
    print("SKIP 10000")
    continue
if i==10025:
    print("FINISH")
    break
print(i)
b="cyka\n"
a=int(input("#"))
if a>=10000:
    print(b*a)
elif a<=10000:
    while True:
        i+=1
        if i==10000:
            print("Breaking!")
            break
        print(i)

2 个答案:

答案 0 :(得分:2)

不确定你想在这个程序中做什么,但我认为你犯了以下错误: -

  1. 您忘记缩进第3行到第10行
  2. 根据你的第一个陈述,i == 10025将打破你的第一个循环。这意味着我将在你的第二个循环中从10025开始并正向递增意味着它永远不会等于10000,因此永远不会突破你的第二个循环。
  3. 解决方案如下: -

    i=0
    while True:
        i+=1
        if i==10000:
            print("SKIP 10000")
            continue
        if i==10025:
            print("FINISH")
            break
        print(i)
    b="cyka\n"
    a=int(input("#"))
    i=0 #reset i here
    if a>=10000:
        print(b*a)
    elif a<=10000:
        while True:
            i+=1
            #if i>=10000: <-- more stable alternative
            if i==10000:
                print("Breaking!")
                break
            print(i)
    

答案 1 :(得分:0)

因为确实没有重置,并且该值与之前的break相同,所以如果你这样做会产生无限循环:

i=0
while True:
    i+=1
    if i==10000:
        print("SKIP 10000")
        continue
    elif i==10025:
        print("FINISH")
        break

print(i)
b="cyka\n"
a=int(input("#"))

if a>=10000:
    print(b*a)

elif a<=10000:
    while True:
        i+=1
        if i==10000:  # you need to change this value if you dont want infinite loop.
            print("Breaking!")
            break

print(i)

我再次检查了你的代码,因为你可以在没有重置的情况下以正确的方式完成一个真正的循环。这应该给你预期的结果:

i=0
while True:
    i+=1
    if i==10000:
        print("SKIP 10000")
        continue
    elif i==10025:
        print("FINISH")
    break
print(i)
while True: # put while true here will fix your problem without reset.
    i=10000
    b="cyka\n"
    a=int(input("#"))
    if a>=10000:
        print(b*a)
    elif a<=10000:
        #while True:   delete this line
        i+=1
    if i==10000:
        print("Breaking!")
    break
    print(i)