How does continue statement work in function? - python

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.

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 can I use conditional to control a while loop between a helper and main() function?

Directions:
Write a helper function to validate user input. Function should take inputs until valid. Invalid inputs return error message and repeat the prompt. Valid inputs return to main().
User inputs "1" to "5" each print a unique string. User input "0" exits program.
Everything should be executed from within a main() function. Only the call to main() and function definitions are global.
import sys
def getValidInput(selection):
if selection == "1":
return print("message_1")
elif selection == "2":
return print("message_2")
elif selection == "3":
return print("message_3")
elif selection == "0":
print("goodbye")
sys.exit()
else:
return print("That is not a valid option.")
def main():
askAgain = True
while askAgain == True:
getValidInput(selection = input("Select number 1, 2, 3. 0 exits program."))
in __name__ == "__main__":
main()
My question/issue is that while the sys.exit works to terminate the execution, I have a feeling it's not supposed to be what I'm using. I need to be able to terminate the program after user inputs "0" using a while loop. Within main(), I tried adding a false conditional to the function
call within main():
askAgain = True
while askAgain == True:
getValidInput(selection = input("Select number 1, 2, 3. 0 exits program."))
if getValidInput(selection = input("Select number 1,2, 3. 0 exits program")) == "0"
askAgain == False
and I tried adding the while loop conditional within getValidInput(), instead of main():
askAgain = True
while askAgain == True:
if selection == "1":
askAgain == True
return print("message_1")
if selection == "0"
askAgain == False
return print("goodbye")
What am I doing wrong here? I know I'm not using the loop conditional correctly, but I've tried it several different ways. The sys.exit() is my backup. The user should be able to enter inputs until 0 is entered and that should be controlled from within main(). How can I use values inputted in getValidInput to change the value of my while loop conditional in main()?
If the program is required to run infinitely until the user inputs 0, your idea to use a boolean variable was already in a right path. However, you can utilize the getValidInput() function to return/assign whether the program should stop or continue running.
Assigning the variable selection in the function call inside the main() function is not needed.
One more tip is, you should be more careful on the brackets.
import sys
def getValidInput(selection):
if selection == "1":
print("message_1")
elif selection == "2":
print("message_2")
elif selection == "3":
print("message_3")
elif selection == "0":
print("goodbye")
else:
print("That is not a valid option.")
# Use this if-else block to determine whether your function should continue running or stop
if selection == '0':
return False
else:
return True
def main():
askAgain = True
while askAgain == True:
askAgain = getValidInput(input("Select number 1, 2, 3. 0 exits program."))
if __name__ == "__main__":
main()
You don't need to have the while loop in your helper function. Your helper function is supposed to do one thing, which is just to check the answer and do something.
What you can do is instead of system.exit, each condition return a bool value and pass it to askAgain.
askAgain = getValidateInput()
Finally a small thing, to follow PEP8 rule, you should use snake case: so asg_again, get_validate_input instead.

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

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.

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