一、内置数值操作
二、math库函数
三、代码演示
import math if __name__ == '__main__': # 7 print(3+4) # 7.0 print(3.0+4.0) # -1 print(3-4) # -1.0 print(3.0-4.0) # 64 4的3次方 print(4**3) # 64.0 print(4.0**3.0) # 5 绝对值 print(abs(5)) # 3.5 print(abs(-3.5)) # 3.33333 除 print(10/3) # 3.33333 print(10.0/3.0) # 3 整除 print(10//3) # 3.0 print(10.0//3.0) # 1 余数或模 print(10%3) # 1.0 print(10.0%3.0) # 3 float转int 直接丢球小数位 print(int(3.9)) # 3 print(int(3.1)) # 3.0 print(float(int(3.2))) # 3 round四舍五入 print(round(3.14)) # 4 print(round(3.50)) pi=3.14159265358 # 3.14 保留小数点 print(round(pi,2)) # 32 字符串与数字转换 print(int("32")) # 32.6 print(float("32.6")) # 3.141592653589793 π print(math.pi) # 2.718281828459045 e print(math.e) # 3.0 平方根 print(math.sqrt(9)) # -0.9880316240928618 正弦 print(math.sin(30)) # 0.15425144988758405 余弦 print(math.cos(30)) # -6.405331196646276 正切 print(math.tan(30)) # 0.0 反正弦 print(math.asin(0)) # 0.0 print(math.acos(1)) # 0.7853981633974483 print(math.atan(1)) # 2.302585092994046 print(math.log(10)) # 1.0 以10为底的对数 print(math.log10(10)) # 6 向上取整 print(math.ceil(5.1)) # 5 向下取整 print(math.floor(5.1))
7 7.0 -1 -1.0 64 64.0 5 3.5 3.3333333333333335 3.3333333333333335 3 3.0 1 1.0 3 3 3.0 3 4 3.14 32 32.6 3.141592653589793 2.718281828459045 3.0 -0.9880316240928618 0.15425144988758405 -6.405331196646276 0.0 0.0 0.7853981633974483 2.302585092994046 1.0 6 5
四、最大值、随机数
import random if __name__ == '__main__': nums = [1, 99, 56, 12]; # 找到最大数 print(max(nums)) # 产生随机数 1-10不包含10 for i in range(10): print(random.randrange(1, 10)) print() # 产生随机数 1-5不包含5 步长为2 for i in range(10): print(random.randrange(1, 6, 2)) print() # 产生随机数 0-1 不包含1 for i in range(10): print(random.random())
99 7 2 2 3 2 2 4 6 4 3 5 5 3 3 1 1 3 3 5 3 0.458486991221416 0.23340284993825433 0.8789451406414406 0.9917952555752739 0.34515078497523477 0.5978918688041688 0.22214095016492852 0.44471808067485497 0.8347324395378312 0.7878854646438388