繁体   English   中英

我怎样才能回到以前的 Python 代码?

[英]How can I go back to previous code in 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语句中,我想将用户发送回choiceOneraw_input() elif语句中,我想让用户选择从隔壁继续前进,或者返回第一个房间,看看另一扇门可能藏着什么秘密。 有没有办法做到这一点? 我不在乎方式是否复杂或其他什么,我只是想让它工作。

你在找一个while循环吗?

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

使用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"之外添加一个打印:

然后在您的代码中添加:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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