再议 input
最后看一个有问题的条件判断。很多同学会用 input() 读取用户的输入,这样可以自己输入,程序运行得更有意思:
birth = input('birth: ')
if birth < 2000:
print('00前')
else:
print('00后')
输入 1982 ,结果报错:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
这是因为 input() 返回的数据类型是 str , str 不能直接和整数比较,必须先把 str 转换成整数。Python提供了 int() 函数来完成这件事情:
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
再次运行,就可以得到正确地结果。但是,如果输入 abc 呢?又会得到一个错误信息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
原来 int() 函数发现一个字符串并不是合法的数字时就会报错,程序就退出了。
如何检查并捕获程序运行期的错误呢?后面的错误和调试会讲到。