繁体   English   中英

两个相似的python代码,一个不起作用

[英]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,循环执行如下:

  1. root=2, pwr=2: 2**2 == 4, 4 < 10, 所以增加pwr
  2. root=2, pwr=3: 2**3 == 8, 8 < 10, 所以增加 pwr (这是 x == 8 中断的地方)
  3. root=2, pwr=4: 2**4 == 16, 16 > 10, 所以增加 root 和 pwr = 2
  4. root=3, pwr=2: 3**2 == 9, 9 < 10, 所以增加 pwr (这是 x == 9 中断的地方)
  5. root=3, pwr=3: 3**3 == 27, 27 > 10 所以增加 root 和 pwr = 2
  6. root=4, pwr=2: 4**2 == 16, 16 > 10 所以增加 root 和 pwr = 2

从那里开始,它将在不增加 pwr 的情况下将 root 增加到无穷大,而 root ** pwr 将保持 > 10,因此永远不会满足您的中断条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM