Python Forum
Basic Doubt in code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Basic Doubt in code (/thread-4473.html)



Basic Doubt in code - prateek3 - Aug-19-2017

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)



RE: Basic Doubt in code - TypesWithSpoons2 - Aug-19-2017

I'm not a expert, but I'm pretty sure its '%s' not '%d'.


RE: Basic Doubt in code - snippsat - Aug-19-2017

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.



RE: Basic Doubt in code - cygnus_X1 - Aug-19-2017

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.


RE: Basic Doubt in code - prateek3 - Aug-19-2017

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.


RE: Basic Doubt in code - sparkz_alot - Aug-19-2017

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.


RE: Basic Doubt in code - ichabod801 - Aug-19-2017

(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.