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:
os.execl(sys.executable, sys.executable, *sys.argv)
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.
Try this:
while True:
# main program
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
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.
Using one while loop:
In [1]: start = 1
...:
...: while True:
...: if start != 1:
...: do_run = raw_input('Restart? y/n:')
...: if do_run == 'y':
...: pass
...: elif do_run == 'n':
...: break
...: else:
...: print 'Invalid input'
...: continue
...:
...: print 'Doing stuff!!!'
...:
...: if start == 1:
...: start = 0
...:
Doing stuff!!!
Restart? y/n:y
Doing stuff!!!
Restart? y/n:f
Invalid input
Restart? y/n:n
In [2]:
You can do this simply with a function. For example:
def script():
# program code here...
restart = raw_input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
script()
if restart == "n" or restart == "no":
print "Script terminating. Goodbye."
script()
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.
Here's a fun way to do it with a decorator:
def restartable(func):
def wrapper(*args,**kwargs):
answer = 'y'
while answer == 'y':
func(*args,**kwargs)
while True:
answer = raw_input('Restart? y/n:')
if answer in ('y','n'):
break
else:
print "invalid answer"
return wrapper
#restartable
def main():
print "foo"
main()
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'.
It is very easy do this
while True:
#do something
again = input("Run again? ")
if 'yes' in again:
continue
else:
print("Good Bye")
break
Basically, in this the while loop will run the program again and again because while loops run if the condition is True so we have made the condition true and as you know True is always true and never false. So, will not stop then after this the main part comes here first we will take input from the user whether they want to continue the program or not then we will say that if user says yes i want to continue then the continue keyword will bring the loop to the top again and will run the program again too and if the user says something else or you can do it in another way if you want to only quit the program if user says no then just add this
elif 'no' in again:
print("Good Bye")
break
else:
print("Invalid Input")
this will look that if there is the 'no' word in the input and if there is then it will break the loop and the program will quit
Related
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:
os.execl(sys.executable, sys.executable, *sys.argv)
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.
Try this:
while True:
# main program
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
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.
Using one while loop:
In [1]: start = 1
...:
...: while True:
...: if start != 1:
...: do_run = raw_input('Restart? y/n:')
...: if do_run == 'y':
...: pass
...: elif do_run == 'n':
...: break
...: else:
...: print 'Invalid input'
...: continue
...:
...: print 'Doing stuff!!!'
...:
...: if start == 1:
...: start = 0
...:
Doing stuff!!!
Restart? y/n:y
Doing stuff!!!
Restart? y/n:f
Invalid input
Restart? y/n:n
In [2]:
You can do this simply with a function. For example:
def script():
# program code here...
restart = raw_input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
script()
if restart == "n" or restart == "no":
print "Script terminating. Goodbye."
script()
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.
Here's a fun way to do it with a decorator:
def restartable(func):
def wrapper(*args,**kwargs):
answer = 'y'
while answer == 'y':
func(*args,**kwargs)
while True:
answer = raw_input('Restart? y/n:')
if answer in ('y','n'):
break
else:
print "invalid answer"
return wrapper
#restartable
def main():
print "foo"
main()
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'.
It is very easy do this
while True:
#do something
again = input("Run again? ")
if 'yes' in again:
continue
else:
print("Good Bye")
break
Basically, in this the while loop will run the program again and again because while loops run if the condition is True so we have made the condition true and as you know True is always true and never false. So, will not stop then after this the main part comes here first we will take input from the user whether they want to continue the program or not then we will say that if user says yes i want to continue then the continue keyword will bring the loop to the top again and will run the program again too and if the user says something else or you can do it in another way if you want to only quit the program if user says no then just add this
elif 'no' in again:
print("Good Bye")
break
else:
print("Invalid Input")
this will look that if there is the 'no' word in the input and if there is then it will break the loop and the program will quit
I'm still super beginner in learning python right now and english is not my native language .I hope there is someone can answer my problem. My concern is how can I end all the loop when enter 'e'. I try to modify the code so that it exit all the loop when enter 'e' but the when I also enter 'm' , it also same when enter 'e' instead I want to return back to the menu loop when I enter 'm'. Thank you. Code below
def A():
print("a")
def B():
print("B")
def Menu():
print("Menu")
print("1.A")
print("2.B")
while True:
Menu()
while True:
option = input("Choose a or b")
if option == 'a':
A()
break
elif option == 'b':
B()
break
else:
print("Choose 'a' or 'b' only")
while True:
repeat = input("'m' or 'e'")
if repeat != 'e' and repeat != 'm':
print("Choose 'm' or 'e' only'")
if repeat == 'm':
break
if repeat == 'e':
break
break
I undestand your problem so I'll give you the only clean solution:
while True: # A loop
while True: # B loop
...
# Now from here...
# ...you want to go here?
If you want to exit both B and A loop from inside B loop, there's only one clean way:
def foo():
while True:
while True:
...
return # Will end both loops
Put the whole thing into a function and replace the "double break" with return.
There's an other solution that I would nickname "boolean label solution" which works in most cases but it's less clean so I will just give you a clue.
flag = true
while flag:
while True:
if (condition_to_exit):
flag = false
break
If you just wish to exit the program after exiting the loops, just use the exit() function:
while True:
...
while True:
...
exit()
I'd recommend creating functions for the user input, this way your code will be cleaner and easier to understand.
Look how clean the main loop looks now, it's very clear what it does:
Executes the Menu function
Lets the user choose whether to execute A or B
Asks user to input "m" or "e"
If user inputs "e" it breaks the loop
That's the steps the main loop has to do, so that's all the code that should be there. Code for checking if the user inputs the right options is not the main loop business, it should be inside a function.
This way you delegate tasks and responsibilities to different parts of the code, which for bigger projects it might not be you who programs them.
The code than be further improved and refactored, for example you might want to use dictionaries for the options of your menu. So each key is an option and the value is the function to be executed. This way your Menu() would be just a loop iterating over the dictionary to display the options and then executing the associated function.
Also you might want to take a look at classes, since all this will fit better encapsulated inside a class.
But first and most important: Keep your code clean, self descriptive and organized.
def A():
print("a")
def B():
print("B")
def Menu():
print("Menu")
print("1.A")
print("2.B")
def ExecuteAorB():
while True:
option = input("Choose a or b")
if option == 'a':
A()
break
elif option == 'b':
B()
break
else:
print("Choose 'a' or 'b' only")
def AskUserMorE():
while True:
repeat = input("'m' or 'e'")
if repeat not in ('e', 'm'):
print("Choose 'm' or 'e' only'")
else:
return repeat
while True:
Menu()
ExecuteAorB()
userInput = AskUserMorE()
if userInput == 'e':
break
So I have this while loop which asks user if he/she wants to repeat the program. All works good but I was trying it out and found out that after user repeats the program and when asked second time if he/she wants to repeat, I choose no. But the program still repeats although it prints that program is closing, how can I fix this?
edit: I've fixed it with changing break with return and adding return after main()
def main():
endFlag = False
while endFlag == False:
# your code here
print_intro()
mode, message=get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
while True:
if ui == "Y":
print(" ")
main()
elif ui == 'N':
endFlag = True
print("Program is closing...")
break
else:
print("wrong input, try again")
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
This is because main() function is being called recursively & endFlag is a local variable.
So when you first put 'y' , then another main() is recursively called from the first main() function.
After you put 'n' which ends this second main() and return to the first main which still in a loop with endFlag (local variable) with value as false.
So, need to change,
Either
endFlag variable as global ( i.e. defined outside main function )
Or,
some program exit function in place of break
The thing is that you're doing recursion over here, i.e. you're calling method main() inside main() and trying to break out of it the way you've done is not gonna work (well, you're know it :) )
Second - you don't need a forever loop inside a first loop, you can do it with one simple loop and break.
Here it is:
def print_intro():
intro = "Welcome to Wolmorse\nThis program encodes and decodes Morse code."
print(intro)
def get_input():
return 'bla', 'bla-bla-bla'
def main():
while True:
# your code here
print_intro()
mode, message = get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
if ui == "Y":
print(" ")
elif ui == 'N':
print("Program is closing...")
break
else:
print("wrong input, try again\n")
main()
this is what you should do:
(BTW this is a piece of example code)
while True
name = input('Enter name:')
print ('Hi '+ name)
exit = input('Do you want to exit?(Y/N)')
if exit == 'N' or 'n':
break
(Im not sure if i put the indents correctly )
You can apply this concept into your code.
I'm a complete newbie to the coding trying my hands on python. While coding a simple program to calculate the age I ran into an error I cannot seem to fix no matter how hard I try. The code is pasted below. The program runs as far as I enter an year in the future, however when an year which has passed is used, the code loops again asking if the year is correct. Any help is appreciated.
from datetime import date
current_year = (date.today().year)
print('What is your age?')
myAge = input()
print('future_year?')
your_age_in_a_future_year= input()
future_age= int(myAge)+ (int(your_age_in_a_future_year)) - int(current_year)
def process ():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = input()
if answer =='yes':
print (future_age)
if answer == 'no':
print ('cya')
while answer != 'yes' or 'no':
print ('enter correct response')
process ()
process()
In this case, your function just needs to contain a while loop with an appropriate condition, and then there is no need to break out from it, or do a recursive call or anything.
def process():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = None
while answer not in ('yes', 'no'):
answer = input()
if answer == 'yes':
print(future_age)
elif answer == 'no':
print('cya')
try
...
if future_age > 0:
print(future_age)
return
else:
print('do you really want to go back in time?, enter "yes" or "no"')
...
I have a main method in Python 2.7.11 that (after its first execution) will ask if the user wants to continue (y/n). The response of 'y' re-executes the while loop I instantiated in main just fine, and erroneous inputs are taken into account and the question is re-asked. However, when the user enters 'n', it does not print 'Goodbye.', it instead exits out of the loop without even reaching the print statement. Here is my code:
def main():
will_continue = 'y' # Default for the first execution
while will_continue == 'y':
# A bunch of execution code here for the program...
# After executing rest of code
will_continue = raw_input('Do you wish to continue? (y/n): ')
while will_continue != 'y' and will_continue != 'n':
if will_continue == 'n':
print 'Goodbye.'
else:
will_continue = raw_input('Invalid input. Do you wish to continue? (y/n): ')
if __name__ == "__main__":
main()
I thought maybe my issue was and in while continue != 'y' and continue != 'n':, so I changed it to while continue != 'y' or continue != 'n':, but this keeps me in an infinite loop of 'Goodbye' being printed if I input 'n', or infinite unresponsiveness if I input 'y'.
Any ideas as to why that print 'Goodbye.' statement won't execute before terminating the main?
You're asking the user for input in the else block. If the user inputted 'n', the while block will terminate in the next iteration, causing your if will_continue == 'n' to never execute. A quick fix for it would be to place your if block outside of the inner while loop.
Alternatively, you can eschew the if block and simply have the program print 'Goodbye' at the end regardless of what happens.
will_continue is never changed in your code above, so it will never be 'n'.
Here is an updated version of your code that works.
def main():
con = 'y' # Default for the first execution
while con == 'y':
# A bunch of execution code here for the program...
# After executing rest of code
con = raw_input('Do you wish to continue? (y/n): ')
while con != 'y' and con != 'n':
con = raw_input('Invalid Input. Type y/n: ')
if con == 'n':
print 'Goodbye.'
if __name__ == "__main__":
main()