Help on basic function call


#1

Trying to pass a variable as a function argument that is inputted by the user. Getting some weird errors. Any help will be appreciated.

Error that I'm getting:
Traceback (most recent call last):
File "python", line 14, in
File "python", line 6, in square
TypeError: unsupported operand type(s) for ** or pow(): 'unicode' and 'int'


def square(original):
    """Returns the square of a number."""
    original = raw_input('Enter a number to be squared:')
    squared = original**2
    print "%d squared is %d." % (n, squared)
    return squared
    
#Call the function 

square(original)


#2

@systemace09508,

raw_input gives you a string
you must convert to an integer or float before using it in a numeric operation..


#3

@systemace09508
Just try it out..

def square(original):
"""Returns the square of a number."""
squared = original**2
print "%d squared is %d." % (original, squared)
return squared

original = raw_input('Enter a number to be squared:')
square(int(original))

"""The reason your are getting this error is, you are accepting the number from user and user can enter any data. It might be string or number. The point is that anything you accept using raw_input you will get as a 'string'. To perform any math operation on you have to convert that 'string' into 'int' first. So in my above snip-code at the time of calling function, I've passed converted value.

The second way is that you can pass same value but before performing math operation you need to convert it into 'int' like...

Call the as it is function
suqare(original)
Before calculating or at the time of calculating do this
suared = int(original) ** 2

Note: Make sure that, if you are writing code, which will accept data from user first check that the given data is valid or not for instance.

If user input the 'string' like "three" or "five" then

Your code should be independent and error free."""

Happy Coding....


#4

This was supremely helpful. Thanks a ton leon and methodsurfer.