简体   繁体   中英

input vs. raw_input: Python Interactive Shell Application?

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?

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.

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

elif s == 'exit':
  break

else:
  print('Undefined input')

This should take care of undefined user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM