【问题标题】:Why is the while loop unable to break?为什么while循环无法中断?
【发布时间】:2021-10-28 11:35:30
【问题描述】:
answer = 5
guess = int(input('Please make a wild number guess: '))
count = 1

while guess != answer:
    count += 1
    int(input('wrong. Please make another guess: '))
    print(f"this is your {count} attempt") 

    if guess == answer:
        break
        print('Correct!!!')

我在输入 5 后没有得到预期的答案。在输入正确答案后,我仍然卡在 while 循环中。

错了。请再猜一猜:5 这是你的第 6 次尝试

【问题讨论】:

    标签: python while-loop break


    【解决方案1】:

    因为您没有在 while 循环中更新“guess”的值,所以将其更改为

    guess = int(input('wrong. Please make another guess: '))
    

    【讨论】:

    • 天哪。多谢。不敢相信我犯了这样的愚蠢错误。
    • 任何时候 :) 记得标记正确答案!
    【解决方案2】:

    正如@Soulfly 所说,您需要更新guess

    另外,我建议改变:

     if guess == answer:
            break
            print('Correct!!!')
    

     if guess == answer:
            print('Correct!!!')
            break
    

    所以在输出打印语句之前循环不会中断。

    【讨论】:

      猜你喜欢
      • 2022-07-31
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多