如何理解Python的数值运算?

Python

1 基本算术运算

1.1 使用规则

– Python解析器相当于一个简单的计算器
– Python解析器可以接受简单的算术表达式
– 运算符可以使加(+)减(-)乘(*)除(/)

1.2 实操理解

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2+2
4
>>> 59 - 5*6
29
>>> (50 - 5.0 * 6) /4
5.0
>>> 8/ 5.0
1.6
>>> quit()

2 相除与求余

2.1 使用规则

– 相除返回的数据类型取决于相除的两个数的数据类型
– 如果相除的两个数都是整数,则返回整型(int)
– 如果相除的两个数任意一个是浮点数(float),则返回浮点数
– 使用“//”云算符相除,相除数的小数点被负略,返回整数
– 使用“%”运算符求余

2.2 实操理解

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 17 /3 # int / int -> int
5
>>> 17 / 3.0 # int /float -> float
5.666666666666667
>>> 17 // 3.0 # explicit floor division discards the fractional part
5.0
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17
>>> quit()

3 求次方

3.1 使用规则

– Python使用“**”运算符来进行求次方

3.2 实操理解

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
>>> quit()

4 使用带变量的运算表达式

4.1 使用规则

– “=”号运算符用于变量赋值
– 等号后的运算式直接存储计算的结果(不显示输出)

4.2 实操理解

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
>>> quit()

5 未定义变量

5.1 使用规则

– 未赋值变量被视为未定义变量
– 使用未定义变量会报错

5.2 实操理解

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> n # try to access an undefined variable
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'n' is not defined
>>> quit()

6 变量类型自动转换

6.1 使用规则

– 混合类型的算术运算整型会自动转换为浮点型

6.1 实操理解

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
>>>

7 调用最后一次运算表达式

7.1 使用规则

– 交互模式下
– 最后执行的表达式会存储到变量“_”中

7.2 实操理解

# python
Python 2.7.5 (default, Aug  4 2017, 00:39:18)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>

参阅文档:
https://docs.python.org/2.7/tutorial/index.html
https://docs.python.org/2.7/

没有评论

发表回复

FTP & SFTP & FTPS
如何使用Python连接FTP?

1 前言 一个问题,一篇文章,一出故事。 笔者遇到一个需要使用Python连接ftp的需求,于是整理 …

Python
如何安装部署pysmb?

1 基础知识 pysmb是一个实验性的SMB/CIFS库 pysmb用Python编写 pysmb实 …

Python
如何安装部署Anaconda3?

1 基础知识 1.1 Anaconda的版本 – Anaconda Enterprise …