这个 python 程序有什么错误?

What is the error in this python program?

我最近才在 python 中学习编码。我正在尝试编写一个程序,其中给定的整数将给出具有根和幂的输出(例如范围设置为 5)。这是代码:

user_input = int (raw_input ('Enter your number: '))
root = 1
pwr = 1
def noint ():
    return 'no intergers were found'

def output ():
    return root, '^', pwr
if user_input < 1:
    print noint ()

elif user_input == 1:
    print output ()

else:
    while root < user_input:
        root = root + 1
        if root == user_input:
            print output()   
        else:
            for power in range(5):
                if root ** power == user_input:
                    pwr = power
                    print output()

现在,如果我尝试将 25 作为输入,则输出为: (5, '^', 2) (25, '^', 2)

但如果我尝试任何质数,如 7,输出为:

(7, '^', 1)

给我额外输出 (25, '^', 2) 的编码有什么问题?

您正在这样做:

while root < user_input:
    root = root + 1
    if root == user_input:
        print output()   

也就是对于root == 24你还是进入了循环,增加到25,然后打印出来,因为root == user_input.

如果您只想要具有最小根值的 (root, power) 对,则:

try:
    while root < user_input:
        root = root + 1
        pwr = 1
        for power in range(5):
            if root ** power == user_input:
                pwr = power
                raise Found
except Found:
    print output()

如果您想要所有 (root, power) 对,则:

while root < user_input:
    root = root + 1
    pwr = 1
    for power in range(5):
        if root ** power == user_input:
            pwr = power
            print output()

问题出在这里:

    if root == user_input:
        print output()   

root == 25 时,您打印 output(),但此时 pwr 仍然是 2,而 root5 , 所以它打印 25 ^ 2。您必须在打印 output 后重置 pwr,或者更好的是,使用参数而不是全局变量。

你可以试试这个(实际上,不需要 root == user_input basecase):

def output(root, pwr):
    return root, '^', pwr

if user_input < 1:
    print noint ()
else:
    for root in range(1, user_input + 1):
        for power in range(5):
            if root ** power == user_input:
                print output(root, power)

问题出在这一行:

if root == user_input:
    print output()

root 达到 25 时,您正在打印 rootpwr,但 pwr 是上一场比赛的 2,您有两个选择,更新 pwr 到 1 或在第一场比赛后打破循环(如@Synergist 回答)。