【问题标题】:Why does my Python while loop not terminate?为什么我的 Python while 循环没有终止?
【发布时间】:2020-10-26 10:43:52
【问题描述】:

我是编程新手,在我的一个项目中遇到了 python while 循环。我将我正在做的事情简化为下面的代码。当 count1 或 count2 达到 2 时,下面的 while 循环不会终止。我在这里缺少什么?

count1 = 0
count2 = 0
while count1 < 2 or count2 < 2:
    print('count 1 : ' + str(count1) + ' count 2: ' + str(count2))

    q = int(input('enter 1 or 2'))

    if q == 1:
        count1 += 1
    if q == 2:
        count2 += 1

【问题讨论】:

  • 将or更改为and
  • 您希望它在 either 大于或等于 2 时终止吗?因为如果是这样,你想要and,而不是or。
  • or在while条件语句中的意思是如果有树,请运行下面的块,所以只有count1和count2都大于等于2,循环才会终止。
  • 我希望它在大于或等于 2 时终止。如果 count1 达到 2,我希望它终止。但是如果 count2 首先达到 2 的值,我也希望它终止。我不在乎哪个 count# 先达到 2,我只希望它在任何一个 count# 达到 2 时终止。

标签: python while-loop


【解决方案1】:

目前,您在while 循环中使用了or 条件。

or 当count1 或count2 小于2 时返回true,当values &gt;= 2 两者都返回false。

因此,在您的代码中,while 循环将在 count1 &gt;= 2 和 count2 &gt;= 2 终止一次。

要在count1 和count2 之一达到2 的值时终止while 循环,请使用and 而不是or,如下所示。

while count1 < 2 and count2 < 2
  ...

【讨论】:

  • 好的,很好。我认为那对我来说很清楚。我没有以正确的方式考虑 while 循环。谢谢!
【解决方案2】:

你可以检查条件为真然后break

count1 = 0
count2 = 0
while True:
    print('count 1 : ' + str(count1) + ' count 2: ' + str(count2))
    q = int(input('enter 1 or 2'))
    if q == 1:
        count1 += 1
    if q == 2:
        count2 += 1
    if count1 > 2 or count2 > 2:
        break

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2017-03-10
    • 2020-10-04
    • 2016-01-19
    • 2013-04-22
    • 2016-09-13
    相关资源
    最近更新 更多