Code is looped again and again - python

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

Related

Exiting a program from an If/ELSE statement with Python

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

Never ending While

In this code I try to call a function. On the other hand its not working the way I want it to work, for it is staying in the loop even though I am changing the loops condition options_secondscenario[0] from 0 to 1 at the end of the Loop. What I want this to do is to move to third_scenario() function. Thanks in advance.
options_secondscenario = ['Whats going on out there?', 'So what now?']
def third_scenario():
print "This is the third scenario"
choiceselection2 = raw_input("> ")
if choiceselection2 == 1:
print "stay"
else:
print "leave"
def dead():
print "You are dead"
exit()
def second_scenario():
print "Conversation 1"
print "Conversation 2"
print "Conversation 3"
print options_secondscenario
choices = options_secondscenario[0]
while choices == options_secondscenario[0]:
choiceselection = raw_input("> ")
if choiceselection == 'Whats going on out there?':
print "Conversation 4"
elif choiceselection == 'Whats up':
print "Nothing"
elif choiceselection == 'what is that':
print "I dont know"
elif choiceselection == 'is':
dead()
else:
third_scenario()
choices == options_secondscenario[1]
second_scenario()
You are trying to change your choices var AFTER the loop (check your indentation). So the while loop never gets a chance to reach this statement.
Also, you are using the compare operator == instead of the assignment operator = like so:
choices = options_secondscenario[1]
That line should be somewhere INSIDE your while loop. Check your indentation.

Python: "expected indent block" dont know how to fix [duplicate]

This question already has answers here:
Why am I getting "IndentationError: expected an indented block"? [duplicate]
(6 answers)
Closed 8 years ago.
Ok, so I have my program but I'm getting an "expected an indent block" and i don't know where it is I believe I have it right but I'm very confused.
##Cave fuction
def cave():
global lvl
global mhp
global exp
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
elif talk == 2:
#put train function here
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
print("Anthing else needed(y/n)")
ant = input("Anthing: ")
if ant == n:
break
else:
mexico = 19 #filler
Put pass (or print statment or anything that executes really) between your if/elif statements. The comments aren't really read as code.
In Python, there is no such thing as empty block like {} in C. If you want block to do nothing, you have to use pass keyword. For example:
if talk == 1:
pass # Put storie function here.
elif talk == 2:
pass # Put storie function here.
This should fix your problem. After line ending with :, next line MUST be intended, and comments do not count to indentation in that respect.
After the condition of if or elif, and after else, an indented block is expected. Something like this:
if condition:
indented_block
elif condition:
indented_block
else:
indented_block
Just a comment as a block:
if condition:
# ...
is not considered, so you have to put something there. One alternative is using a placeholder:
if condition:
pass
pass is a null operation. When it is executed, nothing happens.
You have to put some valid statements inside if-else statements, where you have written put storie function here. Following code will not throw an error as there is some valid statement for each if-else:
def cave():
global lvl
global mhp
global exp
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
pass
elif talk == 2:
#put train function here
pass
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
print("Anthing else needed(y/n)")
ant = input("Anthing: ")
if ant == n:
break
else:
mexico = 19 #filler
you need to enter some statement before the. elif talk == 2:
if talk == 1:
print 1
elif talk == 2:
Your if blocks are empty. Try this
if talk == 1:
pass
#put storie function here
elif talk == 2:
pass
#put train function here
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
if that's the exact code you're running, your problem should be within:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
elif talk == 2:
#put train function here
here you get the comment #put storie function here which is not evaluated as code so basically what python interprets is:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
elif talk == 2:
[…]
whereas it expects:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
print("python wants actual code here in an inner block")
elif talk == 2:
print("python wants actual code here in an inner block as well")
[…]
and thus does not compile

if a user tries an option, and the option is not right, go back to a certain point and try again - Python

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.

How to go back to first if statement if no choices are valid

How can I have Python move to the top of an if statement if no condition is satisfied correctly.
I have a basic if/else statement like this:
print "pick a number, 1 or 2"
a = int(raw_input("> ")
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."
What I want is to prompt the user to make another choice for this if statement without them having to restart the entire program, but am very new to Python and am having trouble finding the answer online anywhere.
A fairly common way to do this is to use a while True loop that will run indefinitely, with break statements to exit the loop when the input is valid:
print "pick a number, 1 or 2"
while True:
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
There is also a nice way here to restrict the number of retries, for example:
print "pick a number, 1 or 2"
for retry in range(5):
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
else:
print "you keep making invalid choices, exiting."
sys.exit(1)
You can use a recursive function
def chk_number(retry)
if retry==1
print "you have made an invalid choice, try again."
a=int(raw_input("> "))
if a == 1:
return "this"
if a == 2:
return "that"
else:
return chk_number(1)
print "Pick a number, 1 or 2"
print chk_number(0)
Use a while loop.
print "pick a number, 1 or 2"
a = None
while a not in (1, 2):
a = int(raw_input("> "))
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."

Categories