Python递归权力

时间:2015-06-29 19:37:33

标签: math recursion exponent

def main():

    base = input('Please Enter An Integer for the Base: ')
    exponent = input ('Please Enter An Exponent: ')

def power (base, exponent):
    if exponent == 0:
        return base
    else :
        return base * power(base, exponent - 1)


main()

SAMPLE OUT: 输入基数的整数:2 输入指数的整数:5 2到5的功率等于32

2 个答案:

答案 0 :(得分:1)

如果这是Python 3,请使用如下字符串格式:

result = power(base, exponent)
print("{} to the power of {} equals {}".format(base, exponent, result))

在Python 2中,

print "%d to the power of %d equals %d" % (base, exponent, result)

答案 1 :(得分:0)

这对我有用,但如果我用10作为基数而2作为指数,我得到1000。试着弄明白为什么数学是错误的。

def main():

   base = float(input('Please Enter An Integer for the Base: '))
   exponent = float(input('Please Enter An Exponent: '))
   result = power(base, exponent)
   print("{} to the power of {} equals {}".format(base, exponent, result))

def power (base, exponent):

   if exponent == 0:
      return base
   else :
      return base * power(base, exponent - 1)
main()