[英]two similar python codes, one doesn't work
I am new to python and trying to do a finger exercise involving finding roots to an integer.我是 python 的新手,并试图做一个手指练习,涉及找到整数的根。 My first (after many trials and errors) attempt was the following:我的第一次(经过多次试验和错误)尝试如下:
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."
This worked for 8 & 9, but got hung up with 10.这适用于 8 和 9,但被 10 挂断了。
My second attempt worked for all three numbers:我的第二次尝试适用于所有三个数字:
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."
Why does the first one get hung up?为什么第一个挂了? I feel I have a basic misunderstanding of how while loops work.我觉得我对 while 循环的工作方式有一个基本的误解。 Please help.请帮忙。
You're getting stuck in你陷入困境
elif root ** pwr > x: #increments root to cycle thru again
root = root + 1
pwr = 2
if root ** 2 > x
setting pwr = 2
in every iteration.如果root ** 2 > x
在每次迭代中设置pwr = 2
。
You need to break the loop somehow if root
gets to big.如果root
变大,您需要以某种方式打破循环。
The hang up here in the while loop is because of a couple things, I think.我认为,在 while 循环中挂断是因为一些事情。
First, as @Baart mentioned above, ax
isn't defined--do you mean x
there?首先,正如上面@Baart 提到的, ax
没有定义——你的意思是x
吗?
Second, with 10 as your x, the loop executes as follows:其次,以 10 作为 x,循环执行如下:
and from there, it will increase root into infinity without increasing pwr, while root ** pwr will remain > 10, and thus never meet your break condition.从那里开始,它将在不增加 pwr 的情况下将 root 增加到无穷大,而 root ** pwr 将保持 > 10,因此永远不会满足您的中断条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.