4

I was working off of the answer in this question: Python Interactive Shell Type Application

My code looks like this

def main():
  while True:
    s = input('> ')

    if s == 'hello':
      print('hi')

    if s == 'exit':
      break

if __name__ == "__main__":
  main()

If I run it, and type hello, I get

  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

How should I be listening for text, and calling different functions based on the result?

2
  • python my_shell.py in terminal Commented Apr 5, 2013 at 18:12
  • 3
    You need raw_input, not input (the latter evaluates what you type as a Python expression). Commented Apr 5, 2013 at 18:13

2 Answers 2

5

You're running it under Python 2.x, where input() actually evaluates what you type as a Python expression. Thus, it's looking for a variable named hello, and, since you haven't defined one, it throws the error. Either use Python 3.x, or use raw_input().

From the parentheses in your print I assume you intended to run it under Python 3.x.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I think I would rather force users to call defined variables, but how do I write a my own error message if they input something that is undefined?
1
if s == 'hello':
  print('hi')

elif s == 'exit':
  break

else:
  print('Undefined input')

This should take care of undefined user input.

2 Comments

This seems to work when using raw_input, but when using input python still throws a NameError rather than just printing 'Undefined Input'
Why don't you use argparse - that is a better way of doing it imo? stackoverflow.com/questions/7427101/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.