while loop, asking user if he wants to repeat the program problem - python

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.

Related

Using Python for default parameters

I am currently learning python and stuck on a coding exercise. I am trying to achieve the result as shown on the image1. I am stuck on the overall code. I also not sure how to incorporate the "quit", so that the program terminates.
Image1
def tester(result):
while tester:
if len(result)< 10:
return print(givenstring)
else:
return print(result)
def main():
givenstring = "too short"
result=input("Write something (quit ends): ")
if __name__ == "__main__":
main()
For your problem, you need to have a variable that is your Boolean (true/false) value and have your while loop reference that. currently your while loop is referencing your function. inside your main function when you get your user input you can have a check that if the input is "quit" or "end" and set you variable that is controlling your loop to false to get out of it.
you also are not calling your tester function from your main function.
You missed into main() function to call your function, like tester(result). But such basics should not be asked here.
def tester(result):
if len(result)< 10 and result != 'quit':
givenstring = "too short"
return print(givenstring)
else:
return print(result)
def main():
result=None
while True:
if result == 'quit':
print("Program ended")
break
else:
result=input("Write something (quit ends): ")
if result.lower() == 'quit':
result = result.lower()
tester(result.lower())
if __name__ == "__main__":
main()

How to restart a program from the top of a Python program? [duplicate]

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

How does continue statement work in function?

i am building scientific calculator. After performing the operation it ask do u want to go back in main menu or Exit
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
continue
else:
break
when user press y it go back to main menu otherwise exit
You can`t use break and continue in function, read tutorial
instead, you can use check in your main loop, and your function must return True or False
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
return True
else:
return False
while True: # your main loop
# some other code
# check on exit
if Again():
continue
else:
break
This can work!
class Cal:
def main_menu(self):
print ("I am in main menu")
def again(self):
x = raw_input("Go back to main menu(Y/N)")
if x == 'y':
self.main_menu()
if __name__ == '__main__':
c = Cal()
c.again()
When you will enter y it will go to the main menu.
Also, continue and break will not work here as they both are applied in loops.
You can use raw_input instead of input as input does not accept string values.

Why isn't my if statement executing its print statement Python 2.7.11

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()

How do I restart a program based on user input?

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

Categories

Resources