1

I'm attempting to run these simple lines of Python code:

myName = input("What is your name?")
print (myName)

if (myName == 'Omar'):
    print ("Omar is great!")
else:
    print ("You are ok")

It runs okay if I run it using IDLE, but once I put it in a text file with a ".py" extension I get the following output and error:

What is your name?omar
Traceback (most recent call last):
  File "hello.py", line 2, in <module>
    myName = input("What is your name?")
  File "<string>", line 1, in <module>
NameError: name 'omar' is not defined

I don't know the error states that 'omar' needs to be defined, even though 'omar' is simply a string input.

Help would be much appreciated, thanks.

slightly_toasted
  • 335
  • 5
  • 18

4 Answers4

3

Use raw_input

myName = raw_input("What is your name?")

input is used in python 3 and its python 2 equivalent is raw_input. input in python 2 wraps raw_input with a call to eval, which is the source of your error. Presumably you are using different versions from IDLE and the command prompt without realising it.

If you need a cross python solution, you might like to take a look at this question How do I use raw_input in Python 3.

Community
  • 1
  • 1
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
0

It looks like your IDLE is configured to use python 3, which has good behavior for the input() function, but you're running python 2 from the command line. In python 2, input doesn't do what you expect it to, and you should use raw_input instead. (raw_input returns the input as a string, which is what you want)

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0
#this is a way of using raw_input
pswrd = raw_input("enter the password ")
if pswrd == "im cool": print "you may pass"
imapancake
  • 11
  • 2
  • Please add a few sentences to explain what your code is doing, so you can get more upvotes for your answer. – Fuzzy Analysis Apr 01 '20 at 07:24
  • Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. [From Review](/review/low-quality-posts/25743844) – double-beep Apr 01 '20 at 10:38
0

Maybe your IDE is configured to use Python 2. I had the same problem. I checked my python version with python3 --version and I had version 3.10.2, but I soon realized that PyCharm was using Python 2.7 by default. So I changed the interpreter.

The procedure of changing the interpreter may differ depending on your IDE. But I think it is no hard task.

TechTycho
  • 134
  • 1
  • 10