读取键盘输入要注意的问题
在Python3中读取键盘输入使用input()函数,它所获取的数据都会存储为字符串类型,如需与其他数据类型作比较运算等,需要进行数据类型转换。
例:
age = input('请输入:')
#将字符串类型的age转换成int类型
age_num = int(age)
if age_num >= 18:
print('成年啦!')
输出结果如下:
请输入:20
成年啦!
如果不进行数据类型转换,程序会报错,如下:
age = input('请输入:')
if age >= 18:
print('成年啦!')
输出结果:
请输入:20
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/python/hello/HelloWorld.py", line 12, in <module>
if age >= 18:
TypeError: '>=' not supported between instances of 'str' and 'int'