1.用户输入函数 input() 的工作原理
函数 input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
>>> message = input("Tell me something, and I will repeat it back to you: ")
Tell me something, and I will repeat it back to you: hello Python!
>>> print(message)
hello Python!
当你使用 input() 时,应该指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息。
2.使用 int() 来获取数值输入
使用函数 input() 时,Python将用户输入解读为字符串,所以一旦你想用用户输入的数据来跟其他类型比较时,就必须做类型转换。
>>> age = input("How old are you ?")
How old are you ?30
>>> age
'30'
如上所示我们得到了一个 30 的字符串。
>>> age >= 30
Traceback (most recent call last):
File "", line 1, in
age >= 30
TypeError: '>=' not supported between instances of 'str'