Ask coding questions

← Back to all posts
Stop python code with function?
EricBromstead

Hello Again, This time I was wondering what function I could use to stop the repl.it python program, I have tried exit() quit() sys.exit() and they stop the code from continuing but don't stop the repl.it from running, any way to fix this?

Answered by JoshDaBosh [earned 5 cycles]
View Answer
Voters
GustavBerntsson
aj44822
avak1g
RaphaelSpoerri
BrandonFerrier
emotionbot
abhiss
EricBromstead
Comments
hotnewtop
JoshDaBosh

if you've learned about user defined functions, you could put all your code into function main() and call it. Whenever you need it to stop running, you would simply just put the statement return in your code.
If you need more help, please link your repl. ^^

EricBromstead

@JoshDaBosh Ok this is what I was thinking but I don't want to have to put a tab on every line of main code... but if this is the only way so be it, also was scrolling through the ask section and basically, all my questions are in like the top 50... So From now on before I post! Look for it in repl talk!

JoshDaBosh

@EricBromstead nice.
quick type (hopefully gets to you before you do it manually) - if you want to indent something in python simply highlight the region and press "tab" or do "command"(or ctrl)+"}".

If you want to unindent something then do "command"(or "ctrl")+"{".

artr

@JoshDaBosh im trying to make my repl go back to the start after an answer, do you have any ideas, would be happy to give you access

26youj

@artr make a loop

timmy_i_chen

sys.exit() will work if it's in project mode (more than one .py file)
https://repl.it/@timmy_i_chen/sys-exit

emotionbot

@timmy_i_chen is there a way to restart it instead of just exiting it?

timmy_i_chen

@emotionbot Not without throwing it in a loop :(

RahulChoubey1

@timmy_i_chen It does work, but it just says that the repl process died unexpectedly.

TylerRush

@RahulChoubey1 Did you figure out how to get the program to end without that unexpectedly error thrown?

RahulChoubey1

@TylerRush I think the point is that the code ended the repl, not the user. Seems intentional.

CoolqB

AFAIK there isn't a function that does this, however there are a few work-arounds.
Through my testing, there are a few things that stop a repl. Either if it gets to the EOF, or an error is raised.
You can mimic either of these.

If you want to get to the end of the program easily, there are two ways I've found:
First, you could wrap your entire program into a function, and return from the function when you want to exit.
Second, you could put your entire program into a try except clause and raise a custom Stop exception:

Alternatively, you could just raise an error like:
raise Exception('Stop program')
however this will create a traceback, which mightn't look pretty :/

RaphaelSpoerri

I had the same problem; Not even raise SystemExit() works.

RahulChoubey1