人工智能学习笔记003-Python运算符
程序员文章站
2022-09-03 21:34:30
注:本笔记对应江灏老师在B站的教学视频https://www.bilibili.com/video/BV1zE411V79p 1.算数运算符+ - * / % ** // a=3;b=7 print(a+b) #加 print(a-b) #减 print(a*b) print(a/b) prin ......
注:本笔记对应江灏老师在b站的教学视频https://www.bilibili.com/video/bv1ze411v79p
1.算数运算符+ - * / % ** //
a=3;b=7 print(a+b) #加 print(a-b) #减 print(a*b) print(a/b) print(a%b) #取余 print(a**b) #乘方 print(a//b) #取整
2.比较运算符 == != < > <= >=
返回结果为true或者flase
a=5;b=20 print(a==b) #等于 print(a!=b) #不等于 print(a>b) #大于 print(a<b) #小于 print(a<=b) #小于等于 print(a>=b) #大于等于
3.赋值运算符= += -= *= /= %= **= //= >>= <<=
4.逻辑运算符and or not
优先级:not > and >or
print(3>4 and 4>3 or 1==3 and 'x'=='x' or 3>3) #f #(【3>4 and 4>3】 or 【1==3 and 'x'=='x'】 or 3>3) print(not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9) #4 # (【not 1】 or 【0 and 1】 or 【3 and 4】 or 【5 and 6】 or 【7 and 8 and 9】) # (【0 or 0】 or 4 or 6 or 9) # (【0 or 4】 or 6 or 9) # (4 or 6 or 9) # 4 print(3 and 4) #4 print(4 and 3) #3 print(0 and 3) #0 print(3 and 0) #0 print(true and false)#false print(false and true)#false print(true and true) #true print(false and false)#false print(3 or 4) #3 print(4 or 3) #4 print(0 or 3) #3 print(3 or 0) #3 print(true or false)#true print(false or true)#true print(true or true) #true print(false or false)#false print(not 3) #false print(not 0) #true print(not true) #false print(not false) #
5.位运算符
按位与运算:&
按位或运算:|
按位异或运算:^
按位取反运算:~
左移动运算:<<
右移动运算:>>
执行二进制操作
a=60 #0011 1100 b=13 #0000 1101 print(a & b)#12 二进制:0000 1100 #00 01 10为0,11为1 print(a | b)#61 二进制:0011 1101 #00为0,01 10 11为1 print(a ^ b)#49 二进制:0011 0001 #01 10为1,11 00为0 print(~ a) #-61二进制:1100 0011 #补码,左一为1,所以为负数(0为负数),再取反加1,为-61 print(a << 2)#240二进制:1111 0000 高位丢弃,低位补0 print(a >> 2)#15 二进制:0000 1111 低位丢弃,高位补0
6.成员运算符in not in
list1 = [1,2,3,4,5] a = 2 b = 6 print(a in list1) #t print(a not in list1) #f print(b in list1) #f print(b not in list1)3 #t
7.身份运算符is is not
is 是判断两个标识符是不是引用自一个对象
is not是判断两个标识符是不是引用自不同对象
x is y,类似于id(x) == id(y)
x is not y,类似与id(x) != id(y)
val1 = 2000 val2 = 2001 val3 = val1 +1 print(val3 is val2) print(val3 == val2) print(id(val3) == id(val2))
8.运算符优先级
9.练习:
x = true y = false z = false if not x or y: #false print(1) elif not x or not y and z: #false print(2) elif not x or y or not y and x: #true print(3) else: print(4)