modnar
Posts: 4
Joined: Sat Jul 01, 2017 5:47 pm

Problem with specific error

Tue Jul 04, 2017 5:43 pm

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

RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Problem with specific error

Tue Jul 04, 2017 10:00 pm

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)

User avatar
Paeryn
Posts: 2986
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Problem with specific error

Tue Jul 04, 2017 11:48 pm

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.
She who travels light — forgot something.

Return to “Python”