
上QQ阅读APP看书,第一时间看更新
1.3.3 数值型和字符串型
计算机对数据进行处理时需要知道它的类型,如“汉字+abcd1234”是字符串型的数据,不能进行数值运算;而“-123.62”是数值型的数据,不能获取其中的部分字符。
Python中的数据类型很多,但最基本的是数值型和字符串型。【例1.1】中使用了浮点型和字符串型。浮点型是数值型的一种,关于数值型,第2章将会系统介绍。
1.浮点型
包含小数的数值就是浮点型数值,它可以表达的数值范围很大,但精度有限。
【例1.1】中变量类型分析如下。
(1)a、b、c这3个变量是浮点型的,无论它们输入时是否包含小数,都将通过float()函数转换成浮点数,然后存放到变量中。例如:

(2)由于t、x、x1、x2存放浮点数运算产生的结果,因此也是浮点型的。例如:

(3)如果a、b、c这3个变量变成整数:

则用于存放对整数进行乘(*)和减(-)运算得到的结果的t是整数:

而用于存放对整数进行除(/)和求平方根(math.sqrt())运算得到的结果的x、x1、x2是浮点数。例如:

2.字符串型
【例1.1】中“a=”“b=”“c=”“x=”“x1=”和“x2=”均是字符串常量。