【问题标题】:Can not figure out how to break out of loop无法弄清楚如何跳出循环
【发布时间】:2013-10-07 00:51:08
【问题描述】:

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

【问题讨论】:

  • 请修正缩进

标签: python loops out


【解决方案1】:

首先,您将一个字母与一个元组进行比较。例如,当您使用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.')

【讨论】:

    【解决方案2】:

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

    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.')
    

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

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多