【问题标题】:while else in python not executing the else [duplicate]而python中的else没有执行else [重复]
【发布时间】:2021-06-18 15:14:39
【问题描述】:

我最近才开始探索python。

所以,我在 python 中读到了 while else ,这听起来很棒,但我无法执行一个简单的代码,我错过了什么?

环境:python 3.8.5 (anaconda)

guess = 0
answer = 5
attempts = 0
while answer != guess:
    attempts += 1
    guess = int(input("Guess: "))
    if attempts >= 3:
        break
else:
    print("You Failed")

根据我的理解,它应该在输入 3 次而不是 5 次后打印“You Failed”。但在执行时,它不会那样做。

对此的任何见解都会非常有帮助。

谢谢。

【问题讨论】:

  • 来自顶级答案here:“else 子句仅在您的 while 条件变为 false 时执行。如果您跳出循环,或者如果引发异常,则不会执行。”
  • 这能回答你的问题吗? Else clause on Python while statement
  • 所以你的目的倒退了。当然,这是一个难以有意义地阅读的结构。老实说,我避免使用它,因为它是一种角落用例,而且我真的不认为它具有直观意义。我想如果您直接将循环与if 进行比较,这是有道理的,但循环不是简单的条件。
  • 您在检查answer == guess 之前增加了attempts 的值。当它进入 while 循环时,尝试次数已经为 1。所以你只给自己 2 次尝试。这是您的代码中要修复的另一个问题
  • 好的,因为我在那里添加了一个 break 语句,while 条件变为 True 并且 else 部分没有执行。那么在这种特殊情况下,我应该在 while if 本身中添加 else 部分吗?像过去一样?所以这不是这个概念的好例子。对吗?

标签: python python-3.x


【解决方案1】:

在 cmets 部分很难解释,所以我将在答案部分尝试回答:

代码初始化:

guess = 0
answer = 5
attempts = 0

迭代1:然后代码第一次进入while循环:

while answer != guess:
    attempts += 1

尝试值为 1answer != guess5 != 0 通过初始化。 但是,用户输入 = 0

然后检查尝试次数是否为 3 次或更多。这里它检查1 >= 3False

if attempts >= 3:
    break

假设猜测 = 8

迭代 2: 第一次使用用户输入值检查 while 语句

while answer != guess:
    attempts += 1

现在尝试值是2 作为answer != guess5 != 8 用户输入。但是,用户输入 = 1

然后检查尝试次数是否为 3 次或更多。这里它检查2 >= 3False

if attempts >= 3:
    break

假设猜测 = 9

迭代 3: 使用用户输入值第二次检查 while 语句

while answer != guess:
    attempts += 1

现在尝试值是3 作为answer != guess5 != 9 用户输入。但是,用户输入 = 2

然后检查尝试次数是否为 3 次或更多。在这里它检查3 >= 3True

if attempts >= 3:
    break

当用户只输入两次时,您会跳出循环,因为 attempts3。此外,用户输入值(即使是5)也不再重要。在再次检查之前,您将退出循环。

既然你跳出了循环,它也不会进入else 子句。这就是为什么您无法将代码转到else 子句的原因。这个程序的设计方式,如果你真的猜对了,代码将进入else子句。当while 条件失败时,else 子句被触发。如果你猜对了,while 条件就会失败。您的打印声明与实际发生的情况相矛盾。

希望这可以帮助您调试代码。

以下是修复代码的方法:

answer = 5
attempts = 0
while guess := int(input("Guess: ")) !=answer:
    attempts += 1
    
    if attempts >= 3:
        print("You Failed")
        break
else:
    print ("Congrats on guessing the correct number")

注意:我使用的是海象运算符。如果您不熟悉它,请在此处阅读有关 walrus 运算符的更多详细信息。

调整你的代码,你可以这样修复它:

answer = 5
attempts = 0
while attempts < 3:
    guess = int(input("Guess: "))
    if guess ==answer:
        print ("Congrats on guessing the correct number")
        break
    attempts +=1
else:
    print ('You Failed')

【讨论】:

    【解决方案2】:

    您的代码看起来不错,为什么在 3 次猜测后没有看到输出 you failed 是因为 break 语句,它会自动终止 while else look

    【讨论】:

    • 尝试运行代码并给出 2 个错误答案,第 3 个作为正确答案。或者更好的是,尝试将5 作为第一个答案?看看你得到什么答案。
    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多