Page 1 of 1

Problem with specific error

Posted: Tue Jul 04, 2017 5:43 pm
by modnar
Hi there, just getting started with python. I have a bit of basic knowledge of the language as well as c#, but im following a tutorial and it has me typing this code but it returns an error. It is supposed to print the line "hello modnar how are you" but then the error is presented. I'm running python 2.7.9, any and all help would be greatly appreciated.

Code: Select all

>>> def hello_there():
        name = input("Type your name: ")
        print("Hi", name, "how are you?")

>>> hello_there()
Type your name: modnar

Traceback (most recent call last):
  File "<pyshell#129>", line 1, in <module>
    hello_there()
  File "<pyshell#127>", line 2, in hello_there
    name = input("Type your name: ")
  File "<string>", line 1, in <module>
NameError: name 'modnar' is not defined

Re: Problem with specific error

Posted: Tue Jul 04, 2017 10:00 pm
by RDS
Your code runs perfectly in Python 3.

(Incidentally, if you are just starting off with Python, surely it is better to start with the latest version)

Re: Problem with specific error

Posted: Tue Jul 04, 2017 11:48 pm
by Paeryn
modnar wrote:Hi there, just getting started with python. I have a bit of basic knowledge of the language as well as c#, but im following a tutorial and it has me typing this code but it returns an error. It is supposed to print the line "hello modnar how are you" but then the error is presented. I'm running python 2.7.9, any and all help would be greatly appreciated.

Code: Select all

>>> def hello_there():
        name = input("Type your name: ")
        print("Hi", name, "how are you?")

>>> hello_there()
Type your name: modnar

Traceback (most recent call last):
  File "<pyshell#129>", line 1, in <module>
    hello_there()
  File "<pyshell#127>", line 2, in hello_there
    name = input("Type your name: ")
  File "<string>", line 1, in <module>
NameError: name 'modnar' is not defined
In Python2 the function input() will try to evaluate what the user types which is why you are getting the error that modnar isn't defined. If you had a variable named modnar then it would return the contents of that variable, but worse is that the user could input some valid Python code and it would actually run it!
In Python2 to get the string that the user enters you use raw_input(). In Python3 they made input() work how Python2's raw_input() does (so it returns the string entered).

But as RDS said, you are better off using Python3 unless you have a compelling reason not to.