检查变量challenge是否在有效值列表中

问题描述 投票:0回答:1

我使用的是 Windows 11 家庭版,Python 3.12.2。我正在玩石头剪刀布应用程序。我想检查用户输入是否是有效的选择。我尝试了 try / except 和 if / in。如果用户输入有效条目以外的值,我想重新启动循环。我已经注释掉了当前的尝试。否则程序运行正常。有建议吗?

import random
valid_values = ["rock", "paper", "scissors", "quit"]

victories = [
    ["paper", "rock"],
    ["rock", "scissors"],
    ["scissors", "paper"]
    ]

# create while loop until user exits
while True:
    # prompt user to challenge computer to a game
    user_input = input("Choose rock, paper, scissors, or quit ")
    challenge = user_input.lower()
    # check if user_input is valid
    # if challenge in valid_values:
    #    continue
    # else:
    #    print("this is not a valid value")
    if challenge == "quit":
        print("OK, bye")
        break
    else:
        # generate random rock, paper, scissors
        guess = random.choice(valid_values[0:2])
        # determine winner and display result
        if challenge == guess:
            print("Tie!")
        elif [challenge, guess] in victories:
            print(f"The {challenge} beats the {guess}, you win!")
        else:
            print(f"The {guess} beats the {challenge}, you lose!")type here

如果条目无效,我想重新启动循环。我要么同时得到无效和赢/输,要么我不能退出。也许是因为继续

python list validation while-loop
1个回答
0
投票

您注释掉的代码很接近,但逻辑相反,因为只有当输入

不是
有效值时,它才应该continue循环:

if challenge not in valid_values:
    print("this is not a valid value")
    continue
© www.soinside.com 2019 - 2024. All rights reserved.