简体   繁体   中英

How can I go back to previous code in Python?

I'm pretty new to programming, but I've got a quick question. I'm trying to write a sort of "choose your own adventure" game, but I've run into a problem. I'm only really as far into if statements in the code, but I want to be able to send the user back to previous code when they type something.

For example:

print "You are in a room with two doors to either side of you."
choiceOne = raw_input("Which way will you go?")
choiceOne = choiceOne.lower()
if choiceOne = "r" or choiceOne = "right":
     print "You go through the right door and find yourself at a dead end."
elif choiceOne = "l" or choiceOne = "left":
     print "You go through the left door and find yourself in a room with one more door."
else:
     print "Please choose left or right."

In the if statement, I want to send the user back to choiceOne 's raw_input() . In the elif statement, I want to give the user the option to either proceed through the next door, or return to the first room to see what secrets the other door may hold. Is there any way to do this? I don't care if the way is complicated or whatever, I just want to get this working.

Are you looking for a while loop?

I think that this website explains it very well: http://www.tutorialspoint.com/python/python_while_loop.htm

count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Good bye!"

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

Use a while loop:

while True:
    print "You are in a room with two doors to either side of you."
    choice_one = raw_input("Which way will you go?").lower()
    if choice_one == "r" or choice_one == "right":
         print "You go through the right door and find yourself at a dead end."
         continue # go back to choice_one 
    elif choice_one == "l" or choice_one == "left":
         print "You go through the left door and find yourself in a room with one more door."
         choice_two = raw_input("Enter 1 return the the first room or 2 to proceed to the next room")
         if choice_two == "1":
            # code go to first room
         else:
             # code go to next room
    else:
         print "Please choose left or right."

You need to use == for a comparison check, = is for assignment.

To break the loop you could add a print outside the loop print "Enter e to quit the game" :

Then in your code add:

elif choice_one == "e":
        print "Goodbye"
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM