1.整数
在python中可使用+,-,*,÷运算,也可使用含有括号运算,其中“**”代表乘方,空格不影响运算。
>>>2+3
5
>>>3 - 2
1
>>>2 * 3
6
>>>3 / 2
1.5
>>>3 ** 2
9
>>>3 ** 3
27
>>>10 ** 6
1000000
>>>2+3*4
14
>>>(2+3) * 4
20
2.浮点数
带有小数点的数字称为浮点数。需要注意的是由于python使用二进制计算,所以会产生不确定尾数。
>>>0.1+0.1
0.2
>>>0.2+0.2
0.4
>>>2 * 0.1
0.2
>>>2 * 0.2
0.4
含有的小数位数
>>>0.2+0.1
0.30000000000000004
>>>3 * 0.1
0.30000000000000004
3.str类型错误
str可将数字形变量或常量改变为字符串变量或常量。
age = 23
message = "Happy "+age+"rd Birthday!"
print(message)
结果为显示错误
Traceback (most recent call last):
File "birthday.py", line 2, in <module>
message = "Happy "+age+"rd Birthday!"
TypeError: Can't convert 'int' object to str implicitly
因为这里python分不清“23”是字符串还是数值。所以需要加上str函数
age = 23
message = "Happy "+str(age)+"rd Birthday!"
print(message)
结果
Happy 23rd Birthday!
4.python2中整数注意事项
python2在进行除法时,会忽略小数部分,只显示整数部分;若要显示小数部分,需要在整数中至少含有一个浮点数
>>>3 / 2
1
>>>3.0 / 2
1.5
>>>3 / 2.0
1.5
>>>3.0 / 2.0
1.5