user8572436
user8572436

Reputation:

Python 3 unable to loop break

I'm new to coding and there is a simple problem I do not understand how to fix. I'm just playing around with what I currently learned in Python. The loop in the second code "print("Breaking!") and break does not break the while loop i+=1. How can I fix this?

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)

Upvotes: 0

Views: 103

Answers (2)

An0n
An0n

Reputation: 733

Since indeed there is no reset, and the value is the same as previous break so it will create infinite loop if you do it this way:

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 reviewed your code again since you can fix a while true loop always if you do it the right way without resetting. This should give you the expected result :

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)

Upvotes: 0

Julien Bongars
Julien Bongars

Reputation: 143

Not sure what you want to do in this program but I think you made the following mistakes:-

  1. You forgot to indent lines 3 through 10
  2. According to your first statement, i == 10025 will break your first loop. This means i will start at 10025 in your second loop and be incremented positively meaning it will never be equal to 10000 and therefore never break out of your second loop.

Solution as follows:-

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)

Upvotes: 2

Related Questions