Learn python with socratica [My notes] - part 5 - Arithmetic

Lesson 6 & 7

Experiments in python2

算术运算是编程中非常基础的部分,那么python中是怎么实现的呢?python2和python3在这个方面又有什么样的区别?

首先介绍的是算术运算的基础:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Let's begin.

# Numbers: int, long, float, complex
# operation: + - * /

# the first thing to operate numbers is that
# both of the numbers are the same type

# for example
x = 5 #int
y = 5L #long

# you can also get long number in this way
long(5)
5L

# ints are narrower than longs
# longs are wider than ints

# also, floats are wider than longs
# all longs can be converted to floats
x = 28L
y = 28.0
float(28)
28.0

# however, not all floats can be converted to longs
# for example
a = 3.14 # float

# try to convert to long, and you will find:
long(a)
3L

用long强制转换3.14这个float类型的数,得到的并不是同一个数。

1
2
3
4
5
# similarly
x = 1.721 # float

1.721 + 0j
(1.721+0j)

同样的,复数也是包含所有浮点数的。

1
2
complex(1.721+0j)
(1.721+0j)
float(1.721+0j)

TypeErrorTraceback (most recent call last)

<ipython-input-9-00c7ec0f6750> in <module>()
----> 1 float(1.721+0j)

TypeError: can't convert complex to float

现在,我们可以得出结论,ints<longs<floats<complex,这在python算术运算中,也起到决定性的作用。在python中,如果是两个类型不同的数做运算,结果是什么类型呢?我们做个实验一探究竟:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
a = 6 # int
b = 3L # long
c = 4.5 # float
d = 2.1 + 0j # complex

# Rule: widen numbers so they are the same type

# Addition
a + b # int + long
9L

# Subtraction
c - b # float - long
1.5

# Multiplication
a * c # int * float
27.0

# Division
d / c # complex / float
(0.4666666666666667+0j)

# integer division
16 / 5 # get the quotient
3

# get the Reminder
16 % 5
1

# want the accurate result
print(float(16)/5)
print(16/float(5))
3.2
3.2

# error -> 0
2/0

ZeroDivisionErrorTraceback (most recent call last)

<ipython-input-17-e8326a161779> in <module>()
----> 1 2/0

ZeroDivisionError: integer division or modulo by zero

总结一下,在python中算术运算会以wider number为基准,运算结果以wider number的类型为准。在除法运算中,有两个注意点:

  1. 如果分数线两侧都是int型,那么运算得到的是整除后quotient部分,想得到余数,使用取余%操作得到,先得到准确结果,可以把分母或者分子做float类型的强制转换。
  2. 分母不可以为0。

Differences in python3

1
2
16 /5
3.2

算术运算在python3中就这一点不同,分数线两边默认是float类型,如果想要得到整除结果,使用一下的运算符号:

1
2
3
4
5
6
# no differnce
16%5
1

16 // 5 # 整除
3

Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-