输入与raw_input:Python交互式Shell应用程序?

时间:2013-04-05 18:09:50

标签: python shell undefined interactive

我正在解决这个问题的答案:Python Interactive Shell Type Application

我的代码看起来像这样

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

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

    if s == 'exit':
      break

if __name__ == "__main__":
  main()

如果我运行它,并输入hello,我会得到

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

我应该如何监听文本,并根据结果调用不同的函数?

2 个答案:

答案 0 :(得分:5)

您在Python 2.x下运行它,其中input()实际上评估您键入的内容为Python表达式。因此,它正在寻找名为hello变量,并且,由于您尚未定义一个,因此会抛出错误。要么使用Python 3.x,要么使用raw_input()

print的括号中我假设您打算在Python 3.x下运行它。

答案 1 :(得分:1)

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

elif s == 'exit':
  break

else:
  print('Undefined input')

这应该处理未定义的用户输入。

相关问题