Usage
看一个有问题的条件判断。很多同学会用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()
函数发现一个字符串并不是合法的数字时就会报错,程序就退出了。
如何检查并捕获程序运行期的错误呢?后面的错误和调试会讲到。
do_if.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 注意:
# input()返回的是字符串
# 必须通过int()将字符串转换为整数
# 才能用于数值比较:
age = int(input('Input your age: '))
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')