Python如何回到之前的代码?

2024-10-16 17:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程很陌生,但我有一个很快的问题。我正试图写一个选择你自己的冒险游戏,但我遇到了一个问题。我只对代码中的if语句进行了深入的研究,但是我希望能够在用户键入内容时将其发送回以前的代码。在

例如:

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."

在if语句中,我想将用户发送回choiceOne的raw_input()。在elif语句中,我想给用户一个选择,要么进入隔壁,要么回到第一个房间,看看另一扇门可能藏着什么秘密。有办法吗?我不在乎这条路是不是很复杂,我只是想让这个工作起来。在

谢谢, 卢克


Tags: or代码用户inrightyougoif
2条回答

使用while循环:

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."

您需要使用==进行比较检查,=用于赋值。在

要中断循环,可以在循环之外添加打印print "Enter e to quit the game"

然后在代码中添加:

^{pr2}$

你在找^{}循环吗?在

我觉得这个网站解释得很好: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!"

^{pr2}$

相关问题 更多 >