Python Forum

Full Version: Recursion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def power(n,p):
    """ Return n to the power p. Works only for positive integers """
    return n*power(n,p-1)
if __name__ == '__main__':
print(power(2,24))


Why does this return an error?
Well, there are two things that could cause errors that I see. One, line 5 needs to be indented or you will get an indentation error. Two, your recursive function has no stop case, so it will recurse forever, and eventually cause a recursion error. For example, take power(3, 2). That will call power(3, 1), which will call power(3, 0), which will call power(3, -1), which will call power(3, -2), and so on. You want to stop and just return n when p == 1.
Read the somehow misunderstandable doc string.
""" Return n to the power p. Works only for positive integers """
That positive was meant for p not n.
(Nov-20-2019, 01:29 AM)leodavinci1990 Wrote: [ -> ]
def power(n,p):
    """ Return n to the power p. Works only for positive integers """
    return n*power(n,p-1)
if __name__ == '__main__':
print(power(2,24))


Why does this return an error?

Please check your indentation @ print part and also check for negative values for p

Try below one:
def power(n,p):
    """ Return n to the power p. Works only for positive integers """
    if p!=0:
        return n*power(n,p-1)
    return 1
if __name__ == '__main__':
    r = power(2,24)
    print(r)
Seems to me that as the guys above say, you need to have a closer look to your indentation @ print part; plus the negative values for p...
def power(base,exp):
    if(exp==1):
        return(base)
    if(exp!=1):
        return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
(Nov-21-2019, 11:03 AM)sumana Wrote: [ -> ]
def power(base,exp): if(exp==1): return(base) if(exp!=1): return(base*power(base,exp-1)) base=int(input("Enter base: ")) exp=int(input("Enter exponential value: ")) print("Result:",power(base,exp))
Thanks. Will make sure I follow that format next time
(Nov-21-2019, 11:03 AM)sumana Wrote: [ -> ]
def power(base,exp):
    if(exp == 1):
        return(base)
    if(exp != 1):
        return(base*power(base,exp-1))
base = int(input("Enter base: "))
exp = int(input("Enter exponential value: "))
print("Result:",power(base, exp))
Above code has several problems:
- What if you enter a negative exponent?
- Exponent can be 0, result would be 1
So valid version of power() looks like:

def power(base, exponent):
    """ Return base to the power exponent. Works only for positive exponents"""
    if exponent == 0:
        return 1
    elif exponent > 0:
        return base * power(base, exponent - 1)
    else:
        raise ValueError("Exponent must be positve!")