-1

我有一个用 Python 完成的字母猜谜游戏。用户可以选择的字母是“a、b、c 和 d”。我知道如何给他们五次尝试,但是当我猜出其中一个正确的字母时,我无法打破循环并祝贺玩家。

    g = 0
    n = ("a", "b", "c", "d")

    print("Welcome to the letter game.\nIn order to win you must guess one of     the\ncorrect numbers.")
    l=input('Take a guess: ');
    for g in range(4):

    if l == n:
        break

        else:
            l=input("Wrong. Try again: ")


    if l == n:
            print('Good job, You guessed one of the acceptable letters.')

    if l != n:
            print('Sorry. You could have chosen a, b, c, or d.')
4

2 回答 2

0

首先,您将一个字母与一个元组进行比较。例如,当你这样做时if l == n,你在说if 'a' == ("a", "b", "c", "d")

我认为你在这里想要的是一个while循环。

guesses = 0
while guesses <= 4:
    l = input('Take a guess: ')
    if l in n: # Use 'in' to check if the input is in the tuple
        print('Good job, You guessed one of the acceptable letters.')
        break # Breaks out of the while-loop
    # The code below runs if the input was wrong. An "else" isn't needed.
    print("Wrong. Try again")
    guesses += 1 # Add one guess
    # Goes back to the beginning of the while loop
else: # This runs if the "break" never occured
    print('Sorry. You could have chosen a, b, c, or d.')
于 2013-10-01T01:19:29.920 回答
0

这会保留您的大部分代码,但会重新排列它以满足您的目标:

n = ("a", "b", "c", "d")
print('Welcome to the letter game. In order to win')
print('you must guess one of the correct numbers.\n')

guess = input('Take a guess: ');
for _ in range(4):
    if guess in n:
        print('Good job, You guessed one of the acceptable letters.')   
        break      
    guess = input("Wrong. Try again: ")
else:
    print('\nSorry. You could have chosen a, b, c, or d.')

我们并不真正关心循环变量的值,为了明确这一点,我们使用 ' _' 代替变量。

于 2013-10-01T01:24:28.593 回答