Python Forum

Full Version: Basic Doubt in code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Well i can simply put a variable in place of 'n' in square(n) but I tried to allow user to enter a number, but this code is not working and showing this error

Traceback (most recent call last):
File "python", line 10, in <module>
File "python", line 3, in square
TypeError: unsupported operand type(s) for ** or pow(): 'unicode' and 'int'

Code
def square(n):
    squared = n ** 2
    print "%d squared is %d." % (n, squared)
    return squared

n=raw_input("enter a no")
square(n)
I'm not a expert, but I'm pretty sure its '%s' not '%d'.
Use code tag BBcode help.
The problem is that raw_input return a string.
You should use Python 3 as a new user.
def square(n):
    squared = n ** 2
    print "{} squared is {}.".format(n, squared)
    # return square print or return choose one

# Make it return integer
n = int(raw_input("enter a no"))
square(n)
Output:
5 squared is 25.
Here's another way in python3:

def square (n):
  print (n, "squared is ", int(n)**2)
  return

n = input("Enter a number: ")
square (n)
I may be wrong but raw_input was dropped in python3 to just input.
thanks snippsat and Tim,for such helpful replies and that was a silly mistake at my end Tongue
Well im doing a basic pyhton course at "codecademy" right now and they use 2.7, but i'll definitely move to 3 as soon as the course end.
I don't know why Codeacadamy (and others) don't wise up and update their sites, videos, blogs, etc to v3.  It's not like they haven't had ample opportunities to do so.  The Python gods have already decreed there will be no v2.8, so, as they say, why "beat a dead horse".  But that is a rant for another day.  If you must need to finish the course, by all means do, but then, as suggested, switch to the latest version of Python.
(Aug-19-2017, 12:14 PM)sparkz_alot Wrote: [ -> ]I don't know why Codeacadamy (and others) don't wise up and update their sites, videos, blogs, etc to v3.  It's not like they haven't had ample opportunities to do so.

They have no incentive to expend the effort. Their customer base is people who want to learn Python, and therefore don't know about Python and the 2.x vs 3.x issues.