def playAgain():
while True:
try:
replay = input("Do you want to play again? ").lower() #Asking user to play again
except ValueError:
print("Sorry, Invalid Entry") #If response invalid, will ask again
continue
if replay in ("yes","y","true","t"):
main()
elif replay in ("no","n","false","f"):
print ("Goodbye")
return
else: #If input is invalid will ask again
print("Invalid entry, Please enter yes or no")
def main():
print ("Hello")
playAgain()
main()
For my homework, I am required to make a quiz. I have got it all to work accept for the play again feature which you can see above. I am having trouble exiting the program. If I type in no the first time it asks me do you want to play again it will exit correctly. The problem I have is if I type in yes the first time and then no the second time, it will not exit. The program will ask me the question again a third time where if I press no it will exit correctly.
I know the solution is probably very obvious but I can't seem to fix it.
In your code, main calls playAgain. Then, if you select to play again, playAgain calls main recursively.
main -> playAgain -> main -> playAgain
^^^
If you return here, only the second playAgain exits, then the program goes back to the main loop in the first playAgain.
To fix it, add return to exit the main loop when the user selects to play again as well:
if replay in ("yes","y","true","t"):
main()
return # here
For Python 2.7:
def playAgain():
while True:
try:
replay = raw_input("Do you want to play again? ").lower() #Asking user to play again
if replay in ("yes","y","true","t"):
main()
return
elif replay in ("no","n","false","f"):
print ("Goodbye")
return
else: #If input is invalid will ask again
print("Invalid entry, Please enter yes or no")
except ValueError:
print("Sorry, Invalid Entry") #If response invalid, will ask again
def main():
print ("Hello")
playAgain()
main()
Related
I'm writing a short program where users pick otions, I wrote a function (Yes/No) for the user to pick wether to return to home or quit program, when the user picks "No", the program is supposed to display a goodbye! message and quit but the loop seems to display the goodbye message but still prompting the user if they want to quit or not.
This is my function
def exit_home():
while True:
user = input("home or exit? (Yes/No)").lower()
if user == "yes":
main()
elif choice == "no":
print(quit)
quit()
print("Bye! ")
continue
else:
break
print("enter a valid input (Yes or No)")
And I get the result below
home or exit? (Yes/No)no
<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10>
Bye!
home or exit? (Yes/No)
Also if there's a neater way of let user exit the program without printing the <IPython.core blah blah blah> I would appreciate the sugesstion.
Thanks
There are several issues in your code:
Remove print(quit) to get rid of
<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10>
Use return to break the loop instead of continue
print after break doesn't make sense because print will never be executed
break doesn't make sense because it breaks the loop, but you want to get into another interation
Corrected code:
while True:
action = input("home or exit? (Yes/No) ").lower()
if action == "yes":
print("call main function...")
elif action == "no":
print("Bye! ")
break
else:
print("enter a valid input (Yes or No)")
Sample output:
home or exit? (Yes/No) yes
call main function...
home or exit? (Yes/No) maybe
enter a valid input (Yes or No)
home or exit? (Yes/No) no
Bye!
<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10> was shown because you printed out the function.
Just this should work.
import sys
elif choice == "no":
print("Bye! ")
sys.exit()
textbar = driver.find_element("xpath",'//*[#id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p')
while(True):
message = input("Please enter the text you want to send to the selected person to stop the program type -exit- : ")
textbar.send_keys(message)
if(message == "exit"):
break
textbar.send_keys(Keys.RETURN)
In your code, you're calling textbar.send_keys(message) before checking if the message is exit. You should move up your if statement so that you exit the program sooner. And put the find_element inside the loop to avoid StaleElementReferenceException. Eg:
while(True):
message = input("Please enter the text you want to send to the selected person. To stop the program, type -exit- : ")
if(message == "exit"):
break
textbar = driver.find_element("xpath",'//*[#id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p')
textbar.send_keys(message)
textbar.send_keys(Keys.RETURN)
When the program achieve any of the if statements the program stops. How to keep it running after achieving an if statement?
def main():
print("Hello i'm your new virtual messenger:")
inside = input();
if inside == "Hello" or "Hi" or "Hey" or "Yo":
print("hello !")
if inside == "Whats's your name":
print("My name is Raito")
if inside == "Who programmed you" or "Who made you" or "Who've made you":
print("it's you LOL, because i think no one will use this")
if inside =="What can you do":
print("Right now nothing special, died waiting to be updated")
else:
print("I Don't know how to answer your question, i told you, im waiting to be updated")
if __name__=='__main__':
main()
Probably you are looking for the while loop, so you want something like this:
def main():
print("Hello I'm your new virtual messenger:")
while True:
inside = input();
if inside in ["Hello","Hi","Hey","Yo"]:
print("hello !")
elif inside == "Whats's your name":
print("My name is Raito")
elif inside in ["Who programmed you","Who made you","Who've made you"]:
print("it's you LOL, because I think no one will use this")
elif inside == "What can you do":
print("Right now nothing special, died waiting to be updated")
else:
print("I Don't know how to answer your question, I told you, I'm waiting to be updated")
if __name__ == '__main__':
main()
With this code you loop forever.
If you want to exit the loop at some point, for example if you read "Exit" from the input, you can use the keyword break (which let you continue with the code after the while loop) like this:
elif inside == "Exit":
break
This lines of code should be as the others "elif" between the "if" and the "else".
I tried to make it only ask "do you want to continue" 3 times but it doesn't seem to work, it just kept on running. How do I fix this? It is a chat-response program which the computer askes one question and the user response.
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
This is the code I have written for it. but it does not work.
import random
name = input("What is your name? ")
def restart():
restart=input('do you want to continue? ')
if restart=='yes':
choice()
else:
print("ok, see you later!")
exit()
def feeling():
response = input("How are you feeling right now {name}?".format(name=name))
if response == "tired":
tired = ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(tired))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def homesick():
response = input("Do you miss your home? ")
if response == "yes":
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def miss():
response = input("Who do you miss?")
if response == "my mom":
print("Mom will be in town soon")
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
The comment from darvark is correct. If you want to keep the rest of your code the same, then I would just modify the restart function to look something like this:
import sys
def restart():
if input('do you want to continue? ') != 'yes':
sys.exit()
This way, if the user responds with anything other than 'yes', the program will quit; however, if they respond with 'yes', then the call to restart will simply do nothing, and your loop should advance to the next iteration.
One more note: It is not recommended to call the exit function within a program, since it is just a helper function to be used when you're running the Python interpreter. Within a program, you should import the sys module and call sys.exit. Source: Difference between exit() and sys.exit() in Python
before anything here is a list of the stuff I've read in the effort to try to understand this situation:
how to check for eof in python
ubuntuforums
what is eof and what is its significance in python
whats-wrong-question-relied-on-files-exceptions-error-eoferror
python docs: exceptions
How-does-one-fix-a-python-EOF-error-when-using-raw_input
Here is my code:
#!/usr.bin/env python
# Errors
error1 = 'Try again'
# Functions
def menu():
print("What would you like to do?")
print("Run")
print("Settings")
print("Quit")
# The line below is where I get the error
menu_option = input("> ")
if 'r' in menu_option:
run()
elif 's' in menu_option:
settings()
elif 'q' in menu_options():
quit()
else:
print(error1)
menu()
Here are my errors (helping me with the other two errors would be very nice of you ):
Traceback (innermost last):
File "C:\Program Files\Python\Tools\idle\ScriptBinding.py", line 131, in run_module_event
execfile(filename, mod.__dict__)
File "C:\Documents and Settings\MyUser\Desktop\MyProgram.py", line 73, in ?
menu()
File "C:\Documents and Settings\MyUser\Desktop\MyProgram.py", line 24, in menu
menu_option = input("> ")
EOFError: EOF while reading a line
I tried changing the code but nothing happened.
This usually happens when/if you're running a Python script in a non-interactive way, for example by running it from an editor.
Please add the lines
import sys
print(sys.stdin)
to the top of your script and report back what output you get.
First of all, you have a typo in your code above...you typed elif 'q' in menu_options(): instead of elif 'q' in menu_option:.
Also, the reason some of the others above got no errors while running it was because they didn't CALL the function after defining it(which is all your code does). IDLE doesn't evaluate a function's contents(except for syntax) until it's called after definition.
I corrected the typo you made and replaced your run,settings and quit functions with pass statements and ran the script...successfully. The only thing that gave me an EOF error was typing the end-of-file combination for IDLE which was CTRL-D in my case(check 'Options'>'Configure Idle'>'Keys'>Custom key bindings>look at the combination next to 'end-of-file'). So, unless you accidentally pressed the key combination, your program should run alright if your run, settings and quit functions work alright(if u're using IDLE)...
#!/usr.bin/env python
error1 = 'Try again'
def menu():
print("What would you like to do?")
print("Run")
print("Settings")
print("Quit")
# The line below is where I get the error
menu_option = input("> ")
if 'r' in menu_option:
pass
elif 's' in menu_option:
pass
elif 'q' in menu_option:
pass
else:
print(error1)
menu()
menu()
This was the script i ran...u can try and see if u still get that error...
try to use raw_input instead of input