输入与raw_input:Python交互式Shell应用程序? [英] input vs. raw_input: Python Interactive Shell Application?

查看:117
本文介绍了输入与raw_input:Python交互式Shell应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决以下问题的答案: Python交互式Shell类型应用程序

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

我的代码如下

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?

推荐答案

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

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().

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

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

这篇关于输入与raw_input:Python交互式Shell应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆