整数
- (同数学用法)
- 对整数执行加减乘除+ - * /
- 用两个乘号表示乘方运算**
- 用括号修改运算优先级,按指定的次序运算
Python 2 中的整数
- 两个整数相处得到的结果稍有不同(计算整数结果采取方式不是四舍五入,直接将小数部分删除) 3 / 2 >>>1
- 避免上述结果,必须有一个操作数为浮点数,从而结果也是浮点数 3.0 / 2 >>>1.5
3 ** 2
(2 + 3)*4
20
浮点数
- 带小数点的数字都成为浮点数
- 结果包含的小数位数可能是不确定的
- 使用函数str()避免类型错误
0.1 + 0.2
0.30000000000000004
age = 23
message = "Happy " + age + "rd Birthday!"
print(message)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-054af83db125> in <module>()
1 # 浮点数案例
2 age = 23
----> 3 message = "Happy " + age + "rd Birthday!"
4 print(message)
TypeError: can only concatenate str (not "int") to str
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
Happy 23rd Birthday!
练习
fav_num = 6
msg = "My favorite number is " + str(fav_num) + "."
print (msg)
My favorite number is 6.