首页 > 解决方案 > 在这种情况下,if 代码块如何从 while 循环停止的地方继续?

问题描述

我根本没有任何编码经验,我刚刚开始学习 Python。

在 John Guttag 的《Introduction to Computation and Programming Using Python With Application to Understanding Data》一书中,第 3 章开头有一段代码示例:

#Find the cube root of a perfect cube
x = int(input('Enter an integer: '))
ans = 0
while ans**3 < abs(x):
    ans = ans + 1
if ans**3 != abs(x):
    print(x, 'is not a perfect cube')
else:
    if x < 0:
        ans = -ans
    print('Cube root of ' + str(x) + ' is ' + str(ans))

我很难理解的是,“while”之外的“if”如何从迭代中循环中断的地方开始?如果是因为 ans 的最后一次迭代使其脱离循环并且还满足 if 条件,那么 if 条件如何对 ans 的值以及循环内的 x 起作用?(ans^3 不等于x 仅在 while 循环内,这部分如何工作:

 if ans**3 != abs(x):
     print(x, 'is not a perfect cube')

我真的不知道还能问这个问题,但这是我在查看书中的代码之前想出的代码,它有效,也许有助于澄清我的确切要求:

x=int(input('Enter an integer: '))
crx=0

while True:
    if crx**3<abs(x):
        crx=crx+1
    elif crx**3==x:
        print('The cube root of',x,'is',str(crx)+'.')
        break
    elif crx**3==-x:
        print('The cube root of',x,'is',str(-crx)+'.')
        break
    else:
        print(x,'is not a perfect cube.')
        break

在我看来,不知何故,我不得不在 while 循环中插入 if 代码块......

先感谢您。

标签: pythonif-statementwhile-loop

解决方案


这不是if回到while循环的结果。让我们检查一下控制流:

x 被设置为字符串中的整数input

ans用 value 初始化0,一个int

x = int(input('Enter an integer: '))
ans = 0

为了检查某物是否有立方根,while 循环取每个大于的整数0并将其立方,如果立方小于x则增加ans1否则ans保存并while退出循环。请注意,如果多维数据集大于或等于 x,则否则涵盖。

while ans**3 < abs(x):
    ans = ans + 1

如果结果ans等于x,则x有一个立方根。如果不是,则x不是立方根。

if ans**3 != abs(x):
    print(x, 'is not a perfect cube')
else:
    if x < 0:
        ans = -ans
    print('Cube root of ' + str(x) + ' is ' + str(ans))

推荐阅读