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.
3
Answers
You’re only breaking out of the for loop currently. You could set a run flag to break out of both loops like this:
You do not need the while loop. It will break out of the for-loop when n reaches 20.
Code:
Output when n starts at 15:
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: