【问题标题】:Python: For loops breaking issuePython:对于循环中断问题
【发布时间】:2016-01-24 05:42:41
【问题描述】:

我正在使用一个 for 循环,在 for 循环内有两个 if 语句,它们都在 for 循环的每次迭代中被检查。我的问题是,一旦其中一个 if-statements = True,那么我希望 True if-statement 停止被检查,并且只检查第二个 if-statement。反之亦然。

print("Guess the numbers it is! Your goal is to guess a two digit number from 00-99. The two digits may be the same.")
numGuessesN = int(input("How many guesses would you like? (2, 3, or 4) "))

for numGuessesN in range (firstGuess, numGuessesN + 1) :
    print("Guess number", numGuessesN)
    userGuessN = int(input("What is your guess? "))



    if (userGuessN == randomNum1) :
        print("You've guessed the first number!") 
        break
    else :
        print("The first number is not", userGuessN)

    if (userGuessN == randomNum2) :
        print("You've guessed the second number!")
        break
    else :
        print("The second number is not", userGuessN)

我知道 if 语句中的中断将完全退出 for 循环,这不是我想要的。但不知何故,如果结果证明该语句为真,我需要 for 循环仅“中断”每个单独的语句,并继续检查剩余的语句直到它为真,或者循环用完迭代。

谢谢各位!我对这一切都很陌生,所以如果我不是很清楚,我很抱歉哈哈。

【问题讨论】:

    标签: for-loop conditional break


    【解决方案1】:

    要么你使用嵌套的 if 语句,要么(如果你有很多,所以你会有很多重复的代码)你设置一个变量

    first_wrong=False
    if bla:
        pass
    else:
        first_wrong=True
    
    if bla2 and not first_wrong:
        pass
    if bla3 and not first_wrong:
        pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 2011-07-15
      • 2018-05-31
      • 2021-04-21
      相关资源
      最近更新 更多