-1
print(f"n before loop is {n}")

while True:
    for i in range(n):
        if n == 20:
            break
        else:
            print(n)
            n = n + 1
Enter n 10
n before loop is 10
10
11
12
13
14
15
16
17
18
19
^CTraceback (most recent call last):
  File "/home/ubuntu/1_5.py", line 5, in <module>
    for i in range(n):
             ^^^^^^^^
KeyboardInterrupt```

As you can see, i had to ctrl+c every time to exit program. It works properly as intended in other programs and exit as it should be. But here in this program it doesn't exit the program but only exits the loop. Thanks for reading my question.
M--
  • 25,431
  • 8
  • 61
  • 93

3 Answers3

1

You do not need the while loop. It will break out of the for-loop when n reaches 20.

Code:

n = int(input("Enter n "))
print(f"n before loop is {n}")


for i in range(n):
    if n == 20:
        break
    else:
        print(n)
        n = n + 1

Output when n starts at 15:

n before loop is 15
15
16
17
18
19
ScottC
  • 3,941
  • 1
  • 6
  • 20
  • i thought so. i was trying to write a program to test how break and continue works in while loops. and this is the result. tnx for the answer – ash-ash-noob-noob Jan 18 '23 at 16:16
0

You're only breaking out of the for loop currently. You could set a run flag to break out of both loops like this:

n = int(input("Enter n "))
print(f"n before loop is {n}")

run = True
while run:
    for i in range(n):
        if n == 20:
            run = False
            break
        else:
            print(n)
            n = n + 1`
jprebys
  • 2,469
  • 1
  • 11
  • 16
-1

break command allows you to terminate a loop, but it allows you to break the loop this command is written in(for-loop), so if you want to terminate the outer loop(while-loop) you can use a flag:

n = int(input("Enter n "))
print(f"n before loop is {n}")

end = False
while True:
    for i in range(n):
        if n == 20:
            end = True
            break
        else:
            print(n)
            n = n + 1
 if end:
     break
  • hi tnx for taking time to answer. the other user also suggested a very similar solution. but since the other one is less complicated than this one, i will go with that. but tnx for answering. good day – ash-ash-noob-noob Jan 18 '23 at 16:14
  • Why use an `if` statement, if you can just use the `while` condition? – gre_gor Jan 18 '23 at 16:44
  • I thought from the question that he wants to break out of nested loops(the outer loop may be for), but in this condition the outer loop is while, but sorry I should have explained the while loop condition – Abdalla Elawady Jan 18 '23 at 17:23