I am attempting to exit a program without using sys.exit()
The user is asked whether they wish to continue and if they input "Yes" a message saying so is printed and the program continues to run. If they input anything else a message saying they chose to exit is printed and then the program is meant to exit.
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
What I am struggling with is what to add to ELSE to return something to my main which will cause the program to exit and how to go about writing that in code.
If you are so much keen about not using sys.exit() you could directly use raise SystemExit. Well this exception is technically raised when you call sys.exit() explicitly. In this way you don't need to import sys at all.
def keep_going():
answer = raw_input("Do you wish to continue?")
if (answer == "yes"):
print ("You have chosen to continue on")
else:
print "You have chosen to quit this program"
raise SystemExit
This answer will give you the alternate possible ways.
Try this:
def main():
while keep_going():
keep_going()
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return True
else:
print "You have chosen to quit this program"
return False
if __name__ == "__main__":
main()
The program will continue calling keep_going() as long as it returns true, that is when a user answers "yes"
An even shorter solution would be to call keep_going() after the "yes" condition:
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
keep_going()
else:
print "You have chosen to quit this program"
Just, return something, and if that is returned, then let your main function exit, either by falling off the end, by using a return statement, or calling sys.exit()/raise SystemExit.
As an example, I'm here returning a string (a different one based on what the user answered):
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return "keep going"
else:
print "You have chosen to quit this program"
return "please exit"
Now, in main, I can test which of these strings keep_going() returned:
def main():
while keep_going() != 'please exit':
# your code here
if __name__ == "__main__":
main()
While strings will work for this purpose, other values are more commonly used for such a task. If keep_going() returned True (instead of "keep going") or False (instead of "please exit"), then main could be written like
def main():
while keep_going():
# your code here
This also reads pretty naturally ("while keep going do your code"). Note that in this case I'm not comparing the return value to something since True and False are truthy variables - and Python's branching control structures (like if and while) know how they work, i.e. there is no need to write keep_going() == True, and indeed it is considered un-pythonic to do so.
You can try this
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
quit()
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 5 years ago.
I'm making a text adventure game. After the title has printed, the function below prompts the player to begin the game by pressing "y". If they enter "y", the function returns "opening". If not, the function advises them to mind their inputs and calls itself to start over.
The function returns correctly if the player hits "y" the first time. The problem I'm having is that if the player enters the wrong input, subsequent attempts to enter "y" do not return correctly. They skip to the bottom of the function and return my error message "this is wrong".
How can I get the function to return correctly after calling itself?
def prompt():
print "Hit 'Y' to begin."
action = raw_input("> ").lower()
if action == "y":
return "opening"
else:
print "For this game to work, you're going to have to get"
print "the hang of hitting the right key."
print "Let's try that again."
prompt()
return "this is wrong"
ret = prompt()
print ret
you are just calling the function again but not returning the value, it should be
print "Let's try that again."
return prompt()
However, you shouldn't be doing this recursively at all...
def prompt():
print "Hit 'Y' to begin."
action = raw_input("> ").lower()
while action != "y":
print "For this game to work, you're going to have to get"
print "the hang of hitting the right key."
print "Let's try that again."
action = raw_input("> ").lower()
return "opening"
ret = prompt()
print ret
use return prompt() inside function
I am stuck on a simple issue. I am attempting to ask the user to choose a desired function from a list. This inputted user string will invoke the chosen function until it finishes running. (It is a lighting sequence). After this sequence ends, I would like to ask the user if he or she wishes to choose another function. If so, continue. If not, exit the code.
I cannot decide if a while true or if statement is the best to achieve this.
Here is my code:
# random functions
def rainbow():
print 'rainbow'
def clover():
print 'clover'
def foo():
print 'eggs'
if __name__ == '__main__':
# here are some random initializations
print 'ctr-c to quit'
user_input = input("choose from the following: ")
if user_input == 'rainbow':
print 'generating'
rainbow()
rainbow()
rainbow()
user_input = input('choose another')
if user_input == 'foo':
clover()
clover()
I would suggest using a while loop here until you get a successful user_input, upon which you'll want to break the loop. Inside the while look you can have your if statements as needed. For example, in your above code, what happens if the user types in "rainboww", it basically just exits the program. It'd be better to have it like this:
while True:
user_input = input('...')
if "good result"
break
else:
continue
while True:
user_input = input("choose from the following: ")
if user_input == "condition a":
do something
elif user_input == "condition b":
do something..
elif any(user_input == keyword for keyword in ["q", "quit"]):
# when meet any quit keyword, use break to terminate the loop
break
else:
# when doesn't find any match, use continue to skip rest statement and goto the beginning of the loop again
continue
while True can meet your requirement. you can use if-elif-else clauses to do different works.
So I am currently learning how to code Python right now. I decided to do a little program where it requires the user to input a word to command the program to do certain things. I have been having the issue though with putting in every variant of capitalization of the word into the code. My question is, how can I prevent this? Any help would be appreciated. Please keep in mind I am learning Python still and may not understand everything. Here is my code:
#This is the main program.
if choice == '1':
print ("Not Availble Yet")
print (" ")
time.sleep(2.5)
main()
#This is if you wish to quit.
if choice =='2':
end = input ("Are you sure you'd like to quit? ")
#These are all the "I'd like to quit" options.
if end == 'yes':
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == 'Yes':
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == 'yEs':
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == ("yeS"):
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
if end == ("YES"):
print ("Closing Program in 5 seconds").lower
time.sleep(5)
quit
#These are all the "I wouldn't like to quit" options.
if end == 'no':
print ("Continuing Program").lower
time.sleep(2.5)
main()
Thank you!
Lowercase the input:
end = input ("Are you sure you'd like to quit? ")
end = end.lower()
Then check for "yes" and "no" only.
(This is an instance of a general principle called "input normalization", a very common way to simplify programs.)
I have the following code:
def begin_game():
print "You landed on planet and see three rooms."
door = int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password = raw_input("Enter your surname>>>")
if door == 1:
medical_room()
if door == 2:
library()
if door == 3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
When I enter door number, I get medical_room function done but then else statement is executed and code starts again over and over.
My question is why else statement is executed? Shouldn't it stop on if statement, execute inside block and stop?
You need to use elif for the second and third if statements. else only considers the statement immediately before it.
Or since it seems that you're looking for switch statement which does not exist in python you could do something like this:
rooms = {
1: medical_room,
2: library,
3: basement,
}
chosen_room = rooms[door]
chosen_room()
You should be using elif, or else every time you input anything other than 3, the else block will be executed, as door != 3 and the else block only considers the preceding if or elif block.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
Currently, your code tests the first if condition (door==1) and associated actions, then it tests the second and third if conditions. Since the third if statement is False (door==1), it will perform the else statement.
You should use elif statements instead of repeated if statements.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()
I am making a quiz game for a school project and I want to make it so that when the user inputs an invalid command, it goes back and tries the input to goto that menu again and brings up the exact same input box and tries the code again. I will post a part where I want this to happen.
#---->TO HERE
if userinput == str("help"):
print ("This is the help menu")
print ("This is how you play")
else:
print ("Invalid Command")
#This is where I want the user to go back and try entering a command again to get the same code to run through again.
#FROM HERE <----
while True:
userinput = input()
if userinput == 'help':
print('This is the help menu')
print('This is how you play')
break
else:
print('Invalid command')
The while loop is used for situations like these. The break statement allows you to 'break' out of a while or for loop. A while True loop will loop forever, unless it encounters the break statement.
There is also a continue statement which allows you to skip the rest of the loop and go back to the beginning, but there's no need to use it here.
See the docs for further reading.
I'm not a fan of infinite loops with breaks, so here's something that I like better:
validCommands = ['help']
userInput = None
while userInput not in validCommands:
userInput = input("enter a command: ").strip()
handleInput(userInput)
def handleInput(userInput):
responses = {'help':['This is the help menu', 'This is how you play']
}
print('\n'.join(responses[userInput]))
questions = {
'quiz_question_1': quiz_question_1,
'quiz_question_2': quiz_question_2
}
def runner(map, start):
next = start
while True:
questions = map[next]
next = questions()
# whatever room you have set here will be the first one to appear
runner(questions, 'quiz_question_1')
def quiz_question_1():
a = raw_input(">")
if a == "correct answer"
return "quiz_question_2"
if a == "incorrect answer"
return "quiz_question_1"
you can add more "rooms" to the in the squiggly brackets. Just make sure that the last room
does NOT have a comma, and that they are in order in which they appear in the code.