I feel like an idiot asking this but is doing quit() the best way to terminate a python programme? Or is there a better way that could gradually stop all while True loops ect instead of just instantly stopping it all? Once again, I feel like an idiot asking this but I'm just curious.
I don't know why you don't want to use quit() but you can use this:
import sys
sys.exit()
Or this:
raise SystemExit(0)
To halt a while loop you can use the break statement. For example:
while True:
if True:
do something #pseudocode
else:
break
The break statement will immediately halt the while loop as soon as the else statement is read by python
You can use the break statement to stop a while loop. Eg:
while True:
if True:
<do something>
else:
break
Generally, the best way to end a Python program is just to let the code run to completion. For example, a script that looks for "hello" in a file could look like this:
# import whatever other modules you want to use
import some_module
# define functions you will use
def check_file(filename, phrase):
with open filename as f:
while True:
# using a while loop, but you might prefer a for loop
line = f.readline()
if not f:
# got to end of file without finding anything
found = False
break
elif phrase in line:
found = True
break
# note: the break commands will exit the loop, then the function will return
return found
# define the code to run if you call this script on its own
# rather than importing it as a module
if __name__ == '__main__':
if check_file("myfile.txt", "hello"):
print("found 'hello' in myfile.txt")
else:
print("'hello' is not in myfile.txt")
# there's no more code to run here, so the script will end
# -- no need to call quit() or sys.exit()
Note that once the phrase is found or the search comes to the end of the file, the code will break out of the loop, and then the rest of the script will run. Eventually, the script will run out of code to run, and Python will exit or return to the interactive command line.
If you want to stop a while True loop, you could set a variable to True and False, you could even work with a counter if you loop has to stop after a specific amount of loops.
for example
x = 0
y = True
while y == True:
<do something>
x = x + 1
if x == 9:
y = False
just a quick example of what you could do, without using a while loop(basically what i wrote above, but then in 1 line.)
x = 10
for i in range(x):
<do something>
To stop a program, I normally use exit() or break.
I hope this somehow helped you, if not; please comment and I'll try helping you!
Related
thanks in advance for the help!
I'm building a simple program; the idea is for it to periodically check whether a variable has changed and, if it has, do something and, if not, check again. Use case: show a graph derived from the user's current URL in their browser; if the URL is unchanged, do nothing, if it changes, redraw the graph.
I'm running into an issue; I want my function to keep running while the condition is met, and if the condition is not met do something else, but then keep running.
Here's my while function code; my IDE and reading are telling me that "continue" is not permitted here: is there another way that I can keep my function active? Conversely, please do let me know if this is a foolish way to achieve what I'm trying to do!
while new_value != previous_value:
#wait
#do something
#put contents of new_value into previous_value
#update new_value from external source (e.g. URL from browser, which may or not be have changed)
else:
#wait
#do nothing
#put contents of new_value into previous_value
#update new_value from external source
continue
that's an alright start. The while loop will stop if the values are identical which is often. Inside the while loop you can add an if statement for the desired result. While True keeps going until stopped.
while True:
#wait for a couple of seconds
if new_value != previous_value:
#do something
#put contents of new_value into previous_value
#update new_value from external source
I would try something like this:
while True:
#wait some seconds if you need
if(new_value != previous_value):
#do something
else:
#update new_value from external source
I would use a while loop to keep your program running, and then use an if/else statement within the loop. Then just use break statement to stop running the loop.
while True:
if new_value != previous_value:
# Run your code
else:
# Run your code
# When I want the loop to end
break
The issue here is that the 'else' statement, when used like this, is being executed once your loop is already broken. As such there is nothing to 'continue' and your IDE is flagging a syntax error.
This is a somewhat obscure Python construct, but it (and the reasoning behind it) are well explained here at 15m53s.
What you're probably meaning to do is this:
while True:
if new_value != previous_value:
# Do one thing
else:
# Do a different thing
# You will need to specify an end condition,
# or it will continue looping indefinitely.
if exit_conditon_met:
break
I hope i can express myself accordingly, as I'm quite new to programming and I'm sure the answer is quite simple but I can't get there... :)
So I have a 'for' loop that executes some functions. Each function has an 'if' statement in it and only does something, if the conditions allow so.
What I want is the loop to reset, as soon as a function's 'if' statement is satisfied.
Edit: I messed up the function :( thx for your answers so far ^^
An example of what i wish would work:
def do_something():
if something == True:
do_some_stuff
return continue
while i < 999:
do_something()
do_something2()
do_something3()
The 'return continue' is the part that doesn't work as I wish and I can't find a solution for that (maybe I don't know what exactly to google for)
You can have 'do_something' return a boolean
def do_something():
if something is True:
do_some_stuff
return True
return False
while i < 999:
if do_something():
continue
do_something2()
do_something3()
There's no function, so there's nothing to return. You can however break out of the while loop once the condition something is met like so:
while i < 999:
if something == True:
do_some_stuff
break
I want to run a Python program function from a main function that controls the program function with
while True:
I'm led to believe this is good practice. I thought a return call in the program function would break me out, but I get stuck in an infinite loop. Typing "n" should break the loop - how do I do it and is this a sensible thing to do?
def main():
while True:
runPgm()
def runPgm():
while True:
a = str(input("Input?: "))
if a == 'n':
break
return
if __name__ == '__main__':
main()
You just need one infinite loop
def main():
runPgm()
def runPgm():
while True:
a = str(input("Input?: "))
if a == 'n':
return
if __name__ == '__main__':
main()
This isn't working because your break statement (and subsequent return) just exits the current call to the runPgm function. But this returns you to the loop in main, which is never broken out of.
In general you can do "multiple breaks" like this by setting a Boolean flag to say you've want to do a further break, which is checked in the outer loop. However, in your case I think the easier solution is simply to only use one of the loops, not both. Just get rid of the main function entirely and call runPgm instead!
There are two things for you in this.
Use single while True loop.
rather break just use return here because function exits as soon as return is reached.
see below python3 code example.
def main():
print(runPgm())
def runPgm():
while True:
a = str(input("Input?: "))
if a == 'n':
return a
if __name__ == '__main__':
main()
The original source for my initial code is the pygame manual, the answers here show that I don't need to follow that method. However, I'm still unsure why the example in pygame resolves itself. But that's beyond the scope of this question and I'm satisfied I don't need to implement it.
I've already ruled out os.exit, sys.exit(), raise SystemExit(0), quit, and exit().
I want to completely stop once one of my multiple while conditions are fulfilled.
while x:
#do something
#for loop
#if a:
#do something
print "Game over"
os.exit
#elif b:
#do something
print "Game over"
os.exit
break
while y:
#(...same form as the previous one^)
#get user input for the next turn
#while 1
#...
#while n
When I play the game, and the game over message is printed on to the screen, it still asks for the user input despite being told to stop.
This is how sys.exit() should work. Sys.exit() should work if you import it and reach it. Maybe more troubleshooting information would be helpful? This works for python and python3
#!/usr/bin/env python
import sys
while 1==1:
print("This will print")
if 2==2:
print("This will also print")
sys.exit()
print("This will not print")
print("This will not print")
This is my terminal output:
Matts-MacBook-Pro:Desktop mw$ ./stupid.py
This will print
This will also print
edit.
As #goosfraba said, sys.exit(0) would probably be best practice. The link provided says no argument can have undefined behavior. Another argument like 1 or "This is an error message" would also work.
With these small alterations, I managed to make this work:
import os
while True:
#do something
#for loop
if False:
#do something
print "Game over A"
os._exit(0)
elif True:
#do something
print "Game over B"
os._exit(0)
break
print "Not over"
Output:
Game over B
Note the lack of the Not over output.
Perhaps _exit(<status>) is what you need?
You should use:
sys.exit(n)
Where the optional n is an integer with the exit status.
Please check: https://docs.python.org/2/library/sys.html
I wanted to ask,
Is there a way that you can re - run any sort of program on Python 3.x or 2.x without the need for a while loop?
For instance, is there any block of code that I can use to do this:
if user says yes:
re - run code from top
else:
end program
For instance, take this example:
output Hello what would you like to do?
if user says internet
response = go to internet.
if response = true
go to start.
else
end program
def internet
open web page.
output Would you like to do anything else?
if input is yes
return True
else
return False
Thanks,
Judy.
Note, the code above is a mock - up.
This works...
>>> from itertools import count
>>> c = count()
>>> for i in c:
... i = input("what is your input? ")
... if str(i) == "internet":
... print "internet"
... elif i == True:
... continue
... else:
... break
...
what is your input? True
what is your input? "internet"
internet
what is your input? "foo"
>>>
But it's still much better as a while loop.
The while is actually the best and cleanest solution here. Remember to place all re-usable functionality in functions or classes. E.g.:
def main():
while True:
fun()
ask user
if user says no:
break
def fun():
# your functionality goes here
if __name__ == "__main__":
main()
while user says no:
if user says yes:
do stuff
break
This gets rid of one of the statements.
You can restart the execution of a script with os.exec*()
Hope this helps!