递归函数名为Power

时间:2015-06-28 13:03:18

标签: python python-2.7 python-3.x recursion

我的代码遇到了一些麻烦。当我运行代码时,会出现第8行的错误,并表示未定义power。我理解有困难,因为我认为已经定义了。有人可以告诉我出错的地方或我需要做什么才能定义power,因为我无法看到它。

#This program has on file containing a main function and a recursive function named power which recursively calculates the value of the power and then returns it.

def main():
    base = int(input('Enter an integer for the base: '))
    expon = int(input('Enter and integer for the exponent: '))

answer = power(base, expon)

print('The base you entered is ', base)
print('The exponent you entered is ', expon)
print(base, 'to the power of', expon, 'equals', answer)

def power(x, y):
    if y == 0:
        return 1
    if y >= 1:
        return x * power(x, y-1)

main()

2 个答案:

答案 0 :(得分:3)

错误是由于使用 power

这一行造成的
answer = power(base, expon)

出现在 define power

这些行之前
def power(x, y):
    if y == 0:
        return 1
    if y >= 1:
        return x * power(x, y-1)

要解决此问题,您需要在使用之前定义power

编辑 - 以下是重新排列代码的方法:

def power(x, y):
    if y == 0:
        return 1
    if y >= 1:
        return x * power(x, y-1)

base = int(input('Enter an integer for the base: '))
expon = int(input('Enter and integer for the exponent: '))
answer = power(base, expon)

print('The base you entered is ', base)
print('The exponent you entered is ', expon)
print(base, 'to the power of', expon, 'equals', answer)

答案 1 :(得分:0)

Python是一种解释型语言,当您运行脚本时,它会逐行运行脚本,因此,如果要在脚本中使用任何变量或函数,则应该已经定义(或从某个库中导入其定义)或者使用它之前的另一个脚本。它不像其他编译语言(如Java)。