input vs. raw_input: Python Interactive Shell Application?

 ̄綄美尐妖づ 提交于 2019-12-20 02:05:40

问题


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?


回答1:


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.




回答2:


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

elif s == 'exit':
  break

else:
  print('Undefined input')

This should take care of undefined user input.



来源:https://stackoverflow.com/questions/15840667/input-vs-raw-input-python-interactive-shell-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!