Python 中的简单算术计算

2022-07-09  本文已影响0人  Ritchie_Li

1. 除法

a, b, c, d, e =3, 2, 2.0, -3, 10

print(a / b)

print(a / c)

输出都是: 1.5

print(d / b)

print(b / a)

print(d / e)

输出: 

-1.5

0.6666666666666666

-0.3

整除 //

print(a//b) 输出:1

print(a//c) 输出:1.0

如果有一个浮点型数据参与整除,结果是浮点型

2. 加法

a, b =1, 2

print(a+b)

输出:3 

a+=b

print(a)

输出:3

import operator

a, b =1, 2

print(operator.add(a, b))

a = operator.iadd(a,b)

print(a)

print("first string " +"second string")

输出:

3

3

first string second string

3. 幂运算

import math

a, b =2, 3

print(a ** b)

print(math.pow(2,3))

输出:

8

8.0

x = 8

math.pow(x, 1/3) 

x**(1/3)

输出:

2.0

2.0

4. 开方

import math

import cmath

c =4

print(math.sqrt(c))

print(cmath.sqrt(c))

输出:

2.0

(2+0j)

5. 减法

a, b =1, 2

print(b-a)

输出:1

import operator

print(operator.sub(b, a))

输出:1

6. 乘法

a, b =2, 3

print(a*b)

输出:6

print(operator.mul(a, b) )

输出:6

上一篇下一篇

猜你喜欢

热点阅读