没有Python(a ** b)的a的b的幂 [英] a to the power of b without (a**b), Python

查看:85
本文介绍了没有Python(a ** b)的a的b的幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Struggling with an exercise that asks me to write a**b without this operator. Tried to write something myself but am not getting correct results. Instead of one value am getting two, both incorrect. Seems like the counter doesnt really increase. May I ask for help? Thanks!

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))


推荐答案

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

Naive implementation(not the the best of solutions but i think you should be able to follow this one):

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


print(powerof(5,2))

希望它有助于。

这篇关于没有Python(a ** b)的a的b的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆