![](/img/trans.png)
[英]How can i make my for loop continue from where it left off in the try and except block? Python 3
[英]How can an if code block continue from where while loop left off in such cases?
我根本没有任何编码经验,我刚刚开始学习 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
初始化为值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))
简单来说 - 循环确保ans
的值是其立方体大于或等于x
的最低(非负)整数。 请注意以下后果:
x
是一个完美的立方体,那么ans
的最终值就是那个立方根(因为我们知道ans**3
必须等于x
。ans
的最终值必须是ans**3
严格大于x
。 特别是,它不会等于它。 所以计算纯粹是在while
循环中完成的——在此之后, if
检查你是否计算了一个精确的立方根,或者你是否没有(在这种情况下,这永远不可能,因为x
不是一个完美的立方体)。 当然,无论哪种情况,它都会向用户打印适当的消息。
(我刚刚用您自己的解决方案看到了编辑 - 是的,正如您所观察到的,这也很好用。很少只有一种方法可以解决代码问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.