小编典典

没有Python(a ** b)的a的b的幂

python

要求我在没有该运算符的情况下写a **
b的练习很费劲。试图自己写点东西,但没有得到正确的结果。取而代之的是取两个值,而不是一个值。似乎计数器并没有真正增加。我可以寻求帮助吗?谢谢!

def powerof(base,exp):
  result=1
  counter=0
  # until counter reaches exponent, go on
  if counter<=exp:
    # result multiplies itself by base, starting at 1
    result=result*base
    # increase counter
    counter=counter+1
    return result
    return counter  # here it says "unreachable code". Can I not return more variables at the same time?
  else:     # counter already reached exponent, stop
    return

# I want to print 2**8. Suprisingly getting two (incorrect) values as a result
print(powerof(2,8))

阅读 173

收藏
2021-01-20

共1个答案

小编典典

天真的实现(不是最好的解决方案,但我认为您应该能够遵循这一点):

def powerof(base, exp):
    results = 1
    for n in range(exp):
        results *= base
    return results


print(powerof(5,2))

希望能帮助到你。

2021-01-20