输入与raw_input:Python交互式Shell应用程序? [英] input vs. raw_input: Python Interactive Shell Application?
问题描述
我正在解决以下问题的答案: 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屋!