Python3学习笔记:数字运算

Python3中只有三种数据类型:整数,浮点数,复数(包括实数和虚数)。我们通过一段代码来看一下显示效果。

if __name__ == '__main__':
    a=1
    b=2
    c=3
    d=4
    e=5.0
    f=3.1
    g=-1
    
    print("a=",a)
    print("b=",b)
    print("c=",c)
    print("d=",d)
    print("e=",e)
    
    print("int(a)=",int(a))
    print("int(e)=",int(e))
    print("float(b)=",float(b))
    print("complex(a)=",complex(a))
    print("complex(a,b)=",complex(a,b))

输出结果为:

a= 1
b= 2
c= 3
d= 4
e= 5.0
int(a)= 1
int(e)= 5
float(b)= 2.0
complex(a)= (1+0j)
complex(a,b)= (1+2j)

可见,

(1)int()可以将浮点类型转换为整型

(2)float()可以将整形转换为浮点类型

(3)complex用于表示复数

我们再来看一下数字运算符:加+,减-,乘*,除/,取余数%。与其它语言不同的是,Python又多了两个运算符,取整//,乘方**

if __name__ == '__main__':
    a=1
    b=2

    print("a+b=",a+b)
    print("a-b=",a-b)
    print("a*b=",a*b)
    print("a/b=",a/b)
    print("a%b=",a%b)
    print("a**b=",a**b)
    print("a//b=",a//b)

运算结果为

a+b= 3
a-b= -1
a*b= 2
a/b= 0.5
a%b= 1
a**b= 1
a//b= 0

相应的,赋值运算符有-=,+=,*=,/=,%=,//=,**=,其作用跟java语言类似。

比较运算符,相对简单,有>,<,>=,<=,==,!=,不再多说。

Python相对其它语言,优势在于运算。常用的简单数学运算公式有如下几个。

需要注意的是,Import math。

import math
if __name__ == '__main__':
    a=1
    b=2
    c=3
    d=4
    e=5.0
    f=3.1
    g=-1
    
    print("ceil(f)=",math.ceil(f))
    print("floor(f)=",math.floor(f))
    print("abs(g)=",abs(g))
    print("sqrt(d)",math.sqrt(d))
    print("round(d)",round(f))
    print("pow(b,d)",pow(b,d))

ceil(),进位取整。(天花板)

floor(),退位取整。(地板)

abs(),取绝对值。

round(),四舍五入。

sqrt(),开方。

pow(),乘方。

运算结果为:

ceil(f)= 4
floor(f)= 3
abs(g)= 1
sqrt(d) 2.0
round(d) 3
pow(b,d) 16


猜你喜欢

转载自blog.csdn.net/daihuimaozideren/article/details/80695603