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

Lesson 6 & 7

Experiments in python2

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

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

# 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类型的数,得到的并不是同一个数。

# similarly
x = 1.721 # float

1.721 + 0j
(1.721+0j)

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

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中,如果是两个类型不同的数做运算,结果是什么类型呢?我们做个实验一探究竟:

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

16 /5
3.2

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

# no differnce
16%5
1

16 // 5 # 整除
3

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IndexFziQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值