
上QQ阅读APP看书,第一时间看更新
2.6 获取用户输入:人工智能程序的眼睛
如果说print像是使用Python编写的人工智能程序的嘴巴,将计算机想要表达的信息通过屏幕呈现在你面前,那么input就像是人工智能程序的眼睛,将用户输入的信息识别后送回程序的大脑。除此之外,在本节中你将会发现,变量不仅可以用来承载数值,也可以用来表示字符串,如图2-11所示。

图2-11 使用input对变量赋值
下面将结合print和input制作一个人机对话的小程序,将其命名为hello.py。这个程序的算法非常简单,即计算机问用户“What is your name?”,用户回答计算机“××”,计算机说“Hello ××”。你可在本书的配套资源中找到这个程序。图2-12展示了实现这个程序的Python代码。

图2-12 hello.py实现代码
图2-13展示了hello.py程序的每一步运行结果。对于程序的最后一条语句,使用input获取回车符的作用是使程序在运行完第二条语句调用print后不会立即退出,当用户在图2-13(c)所示界面中按Enter键后,程序会立即关闭。

(a)第一步

(b)第二步

(c)第三步
图2-13 hello.py程序的每一步运行结果