![](/img/trans.png)
[英]what's different between these two simple python codes? (one works and the other doesn't work)
[英]two similar python codes, one doesn't work
我是 python 的新手,并试图做一个手指练习,涉及找到整数的根。 我的第一次(经过多次试验和错误)尝试如下:
x = int(raw_input("Please pick a positive integer: "))
root = 2
pwr = 2
while pwr < 6: #this is meant to change pwr from 2 to 3 to 4 to 5
if root ** pwr < x and root ** pwr != x:
pwr = pwr + 1
elif root ** pwr == ax:
break
elif root ** pwr > x: #increments root to cycle thru again
root = root + 1
pwr = 2
if root ** pwr == x:
print root, '**', pwr, '=', x
else:
print x, "has no integer roots."
这适用于 8 和 9,但被 10 挂断了。
我的第二次尝试适用于所有三个数字:
x = int(raw_input("Please pick an integer: "))
root = 2
for pwr in range(2,6):
while root ** pwr < abs(x):
root = root + 1
if root ** pwr == abs(x):
break
if root ** pwr == abs(x):
break
root = root + 1
root = 2
if root ** pwr == abs(x):
print root, '**', pwr, '=', x
else:
print x, "has no integer roots."
为什么第一个挂了? 我觉得我对 while 循环的工作方式有一个基本的误解。 请帮忙。
你陷入困境
elif root ** pwr > x: #increments root to cycle thru again
root = root + 1
pwr = 2
如果root ** 2 > x
在每次迭代中设置pwr = 2
。
如果root
变大,您需要以某种方式打破循环。
我认为,在 while 循环中挂断是因为一些事情。
首先,正如上面@Baart 提到的, ax
没有定义——你的意思是x
吗?
其次,以 10 作为 x,循环执行如下:
从那里开始,它将在不增加 pwr 的情况下将 root 增加到无穷大,而 root ** pwr 将保持 > 10,因此永远不会满足您的中断条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.