Functions: Parameters and Arguments - unsupported operand type(s)... error


#1

I'm on this part of the Python course:

Functions
Parameters and Arguments

https://www.codecademy.com/courses/python-beginner-c7VZg/1/3?curriculum_id=4f89dab3d788890003000096

And this is the code I have written

base = raw_input("Gimme some base: ")
exponent = raw_input("Now some exponent: ")

def power(base,exponent):  # Add your parameters here!
    result = base**exponent
    print "%d to the power of %d is %d." % (base, exponent, result)

power(base,exponent)  # Add your arguments here!

Yet I got this error message:

"unsupported operand type(s) for ** or pow(): 'unicode' and 'unicode' "

Pls, help!
Thanks very much!


#2

Replace the ___s with the parameters base and exponent and call power on a base of 37 and a power of 4.

power(37, 4)

When passing raw_input to a numeric function, the values need to be cast as integers...

base = int(raw_input("Gimme some base: "))
exponent = int(raw_input("Now some exponent: "))

power(base,exponent)

Output

Gimme some base:  37
Now some exponent:  4
37 to the power of 4 is 1874161.

#3

Thank you mtf for the advice! The code works now.
But can you explain more to me about the error message?
Is it a rule that I have to define the type of the operand, in this case as numberic values?
Why can't I give a numberic value to the operand while not defining the operand as such?
The function will treat the input as a string?
Thanks again!


#4

 > type(raw_input('...'))
... string
=> <type 'str'>
 > type(raw_input('...'))
... 3.14
=> <type 'str'>

Since the power() function is expecting numbers, we need to convert to one of int or float as the case may be. It is good coding practice to explicity convert numeric string expressions except when printing. Then we may be required to convert a number back to a string.

Python does not coerce numbers in strings to numbers the way JavaScript might.