0

Using Spyder on windows10.

This keeps running infinitely when one might expect the code to exit if i>3:

import time

i = 0
while True:
    i+= 1
    print('hello')
    time.sleep(1)

    if i > 3:
        exit()
        quit()

So neither the quit() nor exit() functions work.

However, this does exit when i>3:

import sys
import time

i = 0
while True:
    i+= 1
    print('hello')
    time.sleep(1)

    if i > 3:
        exit()
        quit()
        sys.exit()

It is noted that the break function works, but the requirement is for the code to terminate (as opposed to breaking out of the loop and continuing).

It is also noted from this question (Code still executes after "quit" or "exit", Python, Spyder) that this is a spyder issue.

Why is this the case and, given the above, what is the best way to exit a while loop preferably without requiring an import ?

D.L
  • 4,339
  • 5
  • 22
  • 45
  • 1
    `quit` and `exit` aren't normal parts of the Python language, they're just hints added in interactive mode so that new users can figure out how to leave the interpreter. `sys.exit()` is what you should be using in an actual script. – jasonharper May 19 '22 at 14:16
  • 1
    "Why is this the case" I don't see how this is unclear from the linked duplicate; there's an answer from a Spyder maintainer that goes into detail. "what is the best way to exit a while loop" `exit` exits *an entire program execution*, not a while loop. If you want to exit an innermost `while` loop, use the `break` keyword - that's what it's for. To exit a function, use `return`. To exit an entire program, your options are to use such an import, raise an uncaught exception, or - almost always the right way - just reach the end of the program naturally, such that there is no more to do. – Karl Knechtel May 19 '22 at 14:20
  • See also https://stackoverflow.com/questions/19747371/python-exit-commands-why-so-many-and-when-should-each-be-used and https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python . – Karl Knechtel May 19 '22 at 14:27
  • Addendum: to break multiple loops, normally it is best to refactor the code such that `return` gets you to the point in the algorithm where you want - i.e., make a function that handles just those loops. The *fact that you want that break* is a hint that the code is giving you, that the loops represent a process that deserves a name. – Karl Knechtel May 19 '22 at 14:30
  • Depends on your installation; that script exits after 4 iterations on my machine, using `exit()` or `quit()`. Both are provided by the `site` module. You should use `sys.exit`, though. – chepner May 19 '22 at 14:32

0 Answers0