我怎么去python的早期行?

时间:2017-08-30 15:27:58

标签: python python-3.x

我正在尝试使用此代码将您带回“是”或“否”?'如果用户键入无效输入,则输入。你能帮助我吗?到目前为止,这是我的代码:

def print_options():
print("~DICE GAME~")
print(" 'p' Print this menu again")
print(" '1' Play")
print(" '2' Instructions")
print(" '3' Quit Game")

choice = "p"
while choice != "3":
    if choice == "1":
        print("****Welcome to the Matrix Game****")
        print("Enter the names for players 1 and 2")
        player1=input("Enter the name of Player 1:")
        player2=input("Enter the name of Player 2:")
        print("Welcome",player1, "and",player2, ", are you ready to conquer 
        the matrix?")
        response=input("Yes or No?")
        if response=="yes" or "Yes" or "yES":
            loadstartgame(player1, player2)
        elif response=="no" or "No" or "nO"?:
            sys.exit()
        else:
            print("invalid choice")
            #here is where i want to go back to the yes or no question

3 个答案:

答案 0 :(得分:3)

您可以通过使用 while True: response=input("Yes or No?") if response.lower() == 'yes': loadstartgame(player1, player2) break elif response.lower() == 'no': sys.exit() print("invalid choice") 循环包含此代码来实现此目的,并且您还可以将if条件更改为更优雅和可读的内容,例如:

lower()

else方法会将字符串更改为小写。您也不需要上一个Button声明。

更新:我将原来的答案编辑得更具体,感谢您的评论。除了是/否的变体之外,这不会接受任何其他答案。

答案 1 :(得分:1)

Python中没有其他语言的goto这样的概念。 *

您要做的是使用围绕输入选项的代码部分的嵌套循环。

response = input("Yes or No?") 
while response.lower() not in ["yes","no"]: #this covers the cases of different upper case letters in the response
    response = input('Please enter either "yes" or "no".')

if response.lower()=="yes":
    loadstartgame(player1, player2)
else:
    sys.exit()   

* goto通常被认为是一种语言的可滥用功能,这是一个长期存在的争论,你可以在互联网上找到它。

答案 2 :(得分:-1)

使用另一个while循环。

        response = 0;
        while response == 0:
            response=input("Yes or No?")
            if response=="yes" or "Yes" or "yES":
                loadstartgame(player1, player2)
            elif response=="no" or "No" or "nO"?:
                sys.exit()
            else:
                print("invalid choice")
                response = 0