简体   繁体   中英

Recursive function to make a^b

My recursive function doesn't seem to be working - it's supposed to take parameters a and b and return a^b .

Here it is:

def power(a, b):
       If b == 0:
               return
       return a * power(a,  b-1)
power(2,  3)

Base case return statement is null. You should return 1 (since a^0 = 1 for a != 0 ).

if b == 0:
    return 1

You might want to handle the case for a = 0 separately though, since 0^0 is mathematically undefined:

if a == 0:
    if b > 0:
        return 0
    else
        # raise an exception here?
def power(a, b):
   if b == 0:
      return 1;
   return a * power(a,  b - 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM