Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursion
#4
(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)
Reply


Messages In This Thread
Recursion - by leodavinci1990 - Nov-20-2019, 01:29 AM
RE: Recursion - by ichabod801 - Nov-20-2019, 01:42 AM
RE: Recursion - by ThomasL - Nov-20-2019, 06:21 AM
RE: Recursion - by Malt - Nov-20-2019, 08:46 AM
RE: Recursion - by ChislaineWijdeven - Nov-20-2019, 10:25 AM
RE: Recursion - by sumana - Nov-21-2019, 11:03 AM
RE: Recursion - by ThomasL - Nov-27-2019, 01:24 PM
RE: Recursion - by leodavinci1990 - Nov-27-2019, 07:16 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020