无法弄清楚如何摆脱循环

时间:2013-10-01 01:12:08

标签: python loops out

我有一个用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.')

2 个答案:

答案 0 :(得分: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.')

答案 1 :(得分: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.')

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