python - 在这种情况下,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 代码块......
先感谢您。
解决方案
这不是if
回到while
循环的结果。让我们检查一下控制流:
x 被设置为字符串中的整数input
ans
用 value 初始化0
,一个int
x = int(input('Enter an integer: '))
ans = 0
为了检查某物是否有立方根,while 循环取每个大于的整数0
并将其立方,如果立方小于,x
则增加ans
,1
否则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))
推荐阅读
- sql - 如何简化包含重复但必要元素的表格?
- java - uWSGI 和 Zuul:所有其他请求都失败
- java - 为什么 BiConsumer 函数接口接受具有返回类型的方法
- html-email - 使用 text-align:left 时如何使 MJML 列居中
- regex - 惰性可选量词应该如何表现?
- asterisk - 想自动安排回拨
- python-3.x - 无法从同一网络上的远程桌面查看 mongodb 服务器桌面上存在的数据库
- java - 如何在java中解码未知的字符串格式
- odoo - 从odoo网站单击时存储字段数据
- android - Call.onStateChanged 方法在通话保持时出现问题