【问题标题】:How do if and else statements behave in a while loop (Python)?if 和 else 语句在 while 循环(Python)中的行为如何?
【发布时间】:2020-10-21 12:27:56
【问题描述】:

我正在观看 this 课程,并在 28:25 包含此代码:

x = 4.5
ans = 0
if x>= 0:
    while ans*ans < x:
        ans = ans +1
    if ans*ans != x:
        print (x, 'is not a perfect square')
    else: print (ans)
else: print (x, ' is a negative number')

Code Image

我没有得到 while 循环——它会一遍又一遍地迭代,然后检查 if 语句吗?还是每次迭代时都会检查 if 语句?我觉得自己很傻!

希望能得到一些帮助——我想如果我更多地运用自己,我会得到帮助的——但这些东西与音乐和哲学非常不同。

(啊——现在明白了——我没有考虑缩进。while 下的 if 和 else 只会在 while 循环中断后发生,因为它们不在 while 循环“内部”。我发誓我每天都变得越来越笨。或者也许我已经很久没有做任何真正超出领域的思考了。)

【问题讨论】:

  • while 会一直迭代,只要ans*ans &lt; x 然后执行ans = ans +1,如果ans*ans &gt;= x 就会中断,并继续它下面的if 语句,即if ans*ans != x:
  • 第6行和第8行的ifelse与第4行的while没有关系
  • 它会一遍又一遍地迭代然后检查 if 语句吗?是的,只要ans*ans &lt; x
  • 它有助于将else: print (ans) 之类的内容转换为带有缩进的多行。它使流程更容易被发现,并且更适合使用调试器单步执行。并学习一个 python 调试器!然后你可以逐行遍历程序,看看它做了什么。

标签: python if-statement while-loop


【解决方案1】:

由于if ans*ans &lt; x: 不在while 循环中,所以while 循环一直迭代到ans*ans &lt; 4.5,然后它检查if 语句。它在每次 while 循环迭代时检查 if ans*ans != x:

【讨论】:

  • 知道了——谢谢。 if 和 else 仅在 while 循环中断后检查。而且我猜 if 和 else 确实涵盖了潜在答案的唯一选项。
【解决方案2】:

trace可以帮助可视化程序流程。由于这里没有太多步骤,您可以显示执行的每一行然后返回源进行比较。

$ python3 -m trace --trace test.py
 --- modulename: test, funcname: <module>
test.py(1): x = 4.5
test.py(2): ans = 0
test.py(3): if x>= 0:
test.py(4):     while ans*ans < x:
test.py(5):         ans = ans +1
test.py(4):     while ans*ans < x:
test.py(5):         ans = ans +1
test.py(4):     while ans*ans < x:
test.py(5):         ans = ans +1
test.py(4):     while ans*ans < x:
test.py(6):     if ans*ans != x:
test.py(7):         print (x, 'is not a perfect square')
4.5 is not a perfect square

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2015-11-08
    • 2022-09-23
    • 1970-01-01
    • 2014-07-01
    • 2015-04-07
    • 2016-10-22
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多