【问题标题】:Stop an Infinite Loop in Python While Statement在 Python While 语句中停止无限循环
【发布时间】:2014-12-29 01:36:16
【问题描述】:

我正在开发一个简单的 python 程序,该程序涉及创建一个圆圈“按钮”,然后让用户在圆圈内单击。如果他们没有点击圈子,就会出现一条消息,说明他们点击了圈子外,应该再试一次。然而,在最后一部分,尽管使用了中断,但我在代码上得到了一个无限循环。有没有人可以帮助查看是否有错误?谢谢!

r = 75

while True:
    # to determine if click is within circle
    length = math.sqrt(((x-100)**2) +((y-250)**2)) 
    if length == r or length < r: 
        break 
    # prints if user does not click within the range
    print("Please click within the spin button") 

【问题讨论】:

  • 当我使用长度的数值时,代码对我来说工作正常,看看你得到的 x 和 y 坐标是否正确以及你使用的公式。

标签: python python-3.x while-loop conditional-statements


【解决方案1】:

xy 永远不会在 while 循环内更新,因此如果它们在第一次迭代中超出您的圈子,length 将始终保持相同的值(大于 r) ,并且永远不会执行break 语句。

另外,请使用if length &gt;= r:。无需分别检查这两个条件。 (从逻辑上讲,它应该是if length &gt; r:,因为点击圆的边缘仍然应该算数。)

【讨论】:

    【解决方案2】:

    如果你想对点击做出反应,你通常会使用某种 GUI 框架,TKinter、GTK、QT、wx 类似的东西或 PythonCard 的包装器。使用 is,您可以连接一个事件,例如单击一个元素到一个方法,该方法应该包含您的代码。这样代码不会在循环中运行,而只会在点击发生时运行。 实际代码很大程度上取决于您选择的 GUI 框架,但您没有提供任何相关信息。

    【讨论】:

      【解决方案3】:
      r = 75
      while True:
          # to determine if click is within circle
          length = math.sqrt(((x-100)**2) +((y-250)**2)) 
          if length == r or length < r: 
              break 
          else:
          # prints if user does not click within the range
          print("Please click within the spin button")
      

      您的代码是正确的,只需要 else 语句。当 if 语句为 false 时运行 else 语句。 所以这里假设 if 语句是正确的,那么代码会中断,但是当 if 语句是 false 时,代码会转到 else 语句并打印 Please click inside the spin button。

      谢谢。

      【讨论】:

        猜你喜欢
        • 2021-05-12
        • 2013-03-26
        • 1970-01-01
        • 2014-07-01
        • 2014-07-13
        • 1970-01-01
        • 2013-05-17
        • 2022-09-29
        • 1970-01-01
        相关资源
        最近更新 更多