0
votes

I am working on a assignment and am encountering this error. NameError: name 'recPower' is not defined

  1. Write a recursive function called pow(base, power) that takes in two numbers. First number is a base and the second number is a power. The function will return the number raised to the power. Thus, if the number is 2 and the power is 4, the function will return 16. (75 points).

  2. Write a main() function that asks for a number and a power. Then calls the recursive function created in step 1 (15 points). DO NOT use the algorithm on page 432 of your book:

    def: recPower (a, n):

    if n == 0:
        return 1
    else:
        factor = recPower (a, n//2)
        if n%2 == 0:
             return factor * factor
         else:
              return  factor * factor * a
    

My current code is as follows

def main():
 a=input("enter base :")
 n=input("enter power :")

 print ("Total = ",recPower(a,n))

main()

def recPower (a,n):

    if n == 0:
        return 1
    else:
        return a*recPower(a,n-1)

` The error I get when I run it is :

Traceback (most recent call last): File ".py", line 7, in main() File ".py", line 5, in main print ("Total = ",recPower(a,n)) NameError: name 'recPower' is not defined

4

4 Answers

3
votes

Functions are stored in identifiers. You have to define it first. Try this one:

def recPower(a, n):
    if n == 0:
        return 1
    else:
        return a * recPower(a, n - 1)


def main():
    a = int(input("enter base :"))
    n = int(input("enter power :"))

    print ("Total = ", recPower(a, n))


main()
1
votes

Define your 'run' function after 'recPower'.

As also mentioned you need to convert the strings that are returned from input() into integers or floats, using either int() or float(). When you try to operations like division you'll get TypeError exceptions.

0
votes

write your method above the main code, because if you write at under the main code method is undefinied

0
votes

functions must be defined before any are used.

try this code

def recPower(a, n):
    # or just a, n = int(a), int(n) is fine
    if isinstance(a, str):
        a = int(a)
    if isinstance(n, str):
        n = int(n)
    if n == 0:
        return 1
    else:
        return a * recPower(a, n - 1)


def main():
    a = input("enter base :")
    n = input("enter power :")

    print ("Total = ", recPower(a, n))


main()