🍉优快云小墨&晓末:https://blog.youkuaiyun.com/jd1813346972
个人介绍: 研一|统计学|干货分享
擅长Python、Matlab、R等主流编程软件
累计十余项国家级比赛奖项,参与研究经费10w、40w级横向
【Python操作基础】系列——运算符,建议收藏!
该篇文章首先讲解了Python中的运算符相关实操知识:包括特殊运算;内置函数;math模块;运算符优先级和结合方向等。
1 特殊运算符
运行程序:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" ##执行多输出
x=2
y=5
y/x #除法
y%x #取余
y//x #整除
x**y #幂次
x==y #相等
x!=y #不等
x is y #判断是否指向同一个引用
x is not y
x in [1,2,3,4]
y in [1,2,3,4]
x not in [1,2,3,4] #判断变量是否在列表中
y//=x #相当于y=y//x
print(x,y)
y//=x+8
print(y)
x=True
y=False
x and y #逻辑运算符
x or y
not x
x=2
y=3
print(x,y)
print(bin(x),bin(y)) #位运算符:将十进制转化为二进制
x&y #按位与
bin(x&y)
bin(x|y) #按位或
bin(x^y) #按位异或
bin(-x)
bin(x<<y)
bin(x>>y)
运行结果:
2.5
1
2
32
False
True
False
True
True
False
False
2 内置函数
运行程序:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" ##执行多输出
pow(2,3) #2的3次方
#dir(_builtins_)#查看内置函数的方法
round(2.991) #四舍五入
round(2.991,2) #四舍五入保留2位小数
运行结果:
8
3
2.99
3 math模块
运行程序:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" ##执行多输出
import math
math.sin(2/5)
math.pi
math.sqrt(2.0)
#math.sqrt(-1)#错误表示
import cmath #导入复数对应函数包
cmath.sqrt(-2)
运行结果:
0.3894183423086505
3.141592653589793
1.4142135623730951
1.4142135623730951j
4 优先级与结合方向
运行程序:
2**2**3
(2**2)**3 #不同运算符优先级不同,方向也不同
x=2+3
x
1+2 and 3+4
运行结果:
256
64
5
7(1, 2, 3)