I'm trying to restart a program using an if-test based on the input from the user.
This code doesn't work, but it's approximately what I'm after:
answer = str(raw_input('Run again? (y/n): '))
if answer == 'n':
print 'Goodbye'
break
elif answer == 'y':
#restart_program???
else:
print 'Invalid input.'
What I'm trying to do is:
- if you answer y - the program restarts from the top
- if you answer n - the program ends (that part works)
- if you enter anything else, it should print 'invalid input. please enter y or n...' or something, and ask you again for new input.
I got really close to a solution with a "while true" loop, but the program either just restarts no matter what you press (except n), or it quits no matter what you press (except y). Any ideas?
This line will unconditionally restart the running program from scratch:
One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.
This can be useful if, for example, you are modifying its code in another window.
You can do this simply with a function. For example:
Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code:
myfunctionname()
. More on this here.Try this:
The inner while loop loops until the input is either
'y'
or'n'
. If the input is'y'
, the while loop starts again (continue
keyword skips the remaining code and goes straight to the next iteration). If the input is'n'
, the program ends.Also note that converting
raw_input
to astr()
is redundant sinceraw_input
already returns a string.Here's a fun way to do it with a decorator:
Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is
'y'
and keep running the code until the answer isn't'y'
.Using one while loop:
I create this program:
Link: https://docs.google.com/document/d/1U8JhesA6zFE5cG1Ia3OsTL6dseq0Vwv_vuIr3kqJm4c/edit