Reputation: 31
I'm having a bit of trouble with my code. When I run the code an error for line 8 occurs and says the power
is not defined. I'm having trouble understanding because I thought that is was defined already. Can someone show me where I went wrong or what I need to do for power
to be defined because I can't see it.
#This program has on file containing a main function and a recursive function named power which recursively calculates the value of the power and then returns it.
def main():
base = int(input('Enter an integer for the base: '))
expon = int(input('Enter and integer for the exponent: '))
answer = power(base, expon)
print('The base you entered is ', base)
print('The exponent you entered is ', expon)
print(base, 'to the power of', expon, 'equals', answer)
def power(x, y):
if y == 0:
return 1
if y >= 1:
return x * power(x, y-1)
main()
Upvotes: 0
Views: 595
Reputation: 13324
The error is caused because this line which uses power
:
answer = power(base, expon)
comes before these lines which define power
:
def power(x, y):
if y == 0:
return 1
if y >= 1:
return x * power(x, y-1)
To fix this, you'll need to define power
before you use it.
Edit - Here's how I would rearrange the code:
def power(x, y):
if y == 0:
return 1
if y >= 1:
return x * power(x, y-1)
base = int(input('Enter an integer for the base: '))
expon = int(input('Enter and integer for the exponent: '))
answer = power(base, expon)
print('The base you entered is ', base)
print('The exponent you entered is ', expon)
print(base, 'to the power of', expon, 'equals', answer)
Upvotes: 3
Reputation: 90979
Python is an interpreted language, when you run the script, it runs the script line by line , so if you are going to use any variable or functions in your script, you should have defined (or imported its definition from some library or another script) prior to using it. It is not like other compiled languages (like Java).
Upvotes: 0