零基础学Python:数值类型和运算符
数值类型
1.int(整形)
在 Python 中定义变量是 不需要指定类型(在其他很多高级语言中都需要)
整形,也被称之为整数。整数就是数学中的数字。
整形在Python中不受长度限制大小范围
定义
使用 type 函数可以查看一个变量的类型
![](https://upload-images.jianshu.io/upload_images/25631092-2e3f21d29e1a8e4b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
2.浮点型(float)
小数类型
小数
![](https://upload-images.jianshu.io/upload_images/25631092-4e285f6f43b138fc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
运算、运算符优先级与整形是一样。
3.类型转化
浮点数转化为整形(显示转化)
![](https://upload-images.jianshu.io/upload_images/25631092-1bfada0e15619f0c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
隐式转化,系统背后默认进行转换
![](https://upload-images.jianshu.io/upload_images/25631092-a30d36bfb36247f1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
运算符
1.算数运算符
因为是整数,所以也可以进行数学中的基本运算。
- 算数运算符是 运算符的一种
-
是完成基本的算术运算使用的符号,用来处理四则运算
除此之外,“+”还可以作为字符串(包括后续要介绍的序列)的连接运算符。
![](https://upload-images.jianshu.io/upload_images/25631092-5f48951d3498d472.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
算数运算符的优先级
- 和数学中的运算符的优先级一致,在 Python 中进行数学计算时,同样也是:
- 先乘除后加减
- 同级运算符是 从左至右 计算
- 可以使用 () 调整计算的优先级
-
以下表格的算数优先级由高到最低顺序排列
-
例如:
2.赋值运算符
以下假设变量a为10,变量b为20:
![](https://upload-images.jianshu.io/upload_images/25631092-50f6cd5261e10966.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
3.身份运算符
is 比较的是两个实例对象是不是完全相同,它们是不是同一个对象,占用的内存地址是否相同。莱布尼茨说过:“世界上没有两片完全相同的叶子”,这个is正是这样的比较,比较是不是同一片叶子(即比较的id是否相同,这id类似于人的身份证标识)。
身份运算符用于比较两个对象的存储单元
![](https://upload-images.jianshu.io/upload_images/25631092-08df178f44b1700d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
id() 函数用于获取对象内存地址。
身份运算符案例:
![](https://upload-images.jianshu.io/upload_images/25631092-16d868a0c0ba6178.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
内存驻留
布尔类型(bool)
![](https://upload-images.jianshu.io/upload_images/25631092-0e8ea02ce5dc18c7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-f10311bf89549e52.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-7b4a9d53ad9a38f5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
1.比较运算符
![](https://upload-images.jianshu.io/upload_images/25631092-0a62c90b25a7b402.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
2.逻辑运算符
Python语言支持逻辑运算符,以下假设变量 a 为 10, b为 20:
![](https://upload-images.jianshu.io/upload_images/25631092-9747a61f04777758.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
逻辑运算符案例:
![](https://upload-images.jianshu.io/upload_images/25631092-4476f98ca6e6e82a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
3.运算符优先级
以下表格列出了从最高到最低优先级的所有运算符:
![](https://upload-images.jianshu.io/upload_images/25631092-8eacf3801af6a1d5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
案例:运算符优先级
![](https://upload-images.jianshu.io/upload_images/25631092-19601ee41051a012.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)