python05入門——基本運算子
阿新 • • 發佈:2020-11-27
目錄
一、算術運算子
+、-、*、/、**、%、//
print(10 + 3) # 輸出:13 print(10 - 3) # 輸出:7 print(10 * 3) # 輸出:30 print(10 / 3) # 輸出:3.3333333333333335 print(10 ** 3) # 次方 輸出:1000 print(10 % 3) # 取餘 輸出:1 print(10 // 3) # 地板除——保留整數 輸出:3
二、比較運算子
=、==、>、<、>=、<=、!=
x=20
y=23
print(x==y) # ==是否相等,輸出False
print(x!=y) # !=是否不相等,輸出True
注意:數字型別之間可以比較大小,但不可以與字串之間進行比較
x=22
b="123"
print(x > b)
# 報錯:TypeError: '>' not supported between instances of 'int' and 'str'
# 字串跟整型數值進行比較,型別不匹配導致報錯
同類型之間可以進行比較,str按照ascii碼錶進行比較,列表按照索引進行比較
print("abc" > "az") # 輸出:False
print([1,2,3] < [1,3,4]) # 輸出:True
三、賦值運算子
+、+=、-=、*=、/=、**
3.1 增量賦值
age=10
age +=2 # age =age+2
age -=2 # age = age-2
age **=2 # age = age*age
age *=2 # age = age*2
age /=2 # age = age/2
print(age)
3.2 鏈式賦值
x=10 y=x z=y x=y=z=10 print(id(x)) print(id(y)) print(id(z))
3.3 交叉賦值
x=10
y=20
# 第一種
temp=x # 把x再賦值一次給一個變數名
x=y
y=temp
# 第二種
x,y=y,x
print(x,y)
3.4 解壓賦值
salary = [1.1,2.2,3.3,4.4,5.5]
mon1=salary[0]
mon2=salary[1]
mon3=salary[2]
mon4=salary[3]
mon5=salary[4]
mon1,mon2,mon3,mon4,mon5 =salary
print(mon1,mon2,mon3,mon4,mon5)
# 變數名多一個不行少一個也不行,必須與值一一對應
# mon1,mon2,mon3,mon4,mon5,mon6=salary
# mon1,mon2,mon3,mon4=salary
# 報錯:ValueError: not enough values to unpack(expected 6, got 5)
# 期望有5個返回值,但函式有6返回值
取前三個值
*代表所有,_下劃線相當於一個變數名,把不需要解壓的全部賦值給下劃線
mon1,mon2,mon3,*_=salary
print(mon1,mon2,mon3) # 輸出:1.1 2.2 3.3
# 取下劃線內所有的值
print(_) # 輸出:[4.4, 5.5]
取前2個和最後一個
mon1,mon2,*_,mon5=salary
print(mon1,mon2,mon5) # 輸出:1.1 2.2 5.5
解壓字典取出的是key
dic={"k1":111,"k2":222,"k3":333}
x,y,z=dic
print(x,y,z) # 輸出:k1 k2 k3
x,*_=dic
print(x) # 輸出:k1
# 通過key取value
print(dic[x]) # 輸出:111
# 注意:字典取值用[]
四、邏輯運算子
優先順序: not > and > or
not:代表把緊跟其後的條件結果取反
print(not 10 > 3) # False
and:連線左右兩個條件,左右兩個條件必須同時成立,最終結果才為True
print(True and 1 > 0 and "aaa" == "aaa") # True
print(True and 1 < 0 and "aaa" == "aaa") # False
or:連線左右兩個條件,左右兩個條件但凡是有一個成立的,最終結果才為True
print(True or 1 < 0 or "aaa" == "aaa") # True
print(False or 1 < 0 or "aaa" != "aaa") # False
# False False False
三者混合用時推薦用括號區分優先順序,把not後面的條件當成一個整體括起
# res = 3 > 4 and 4 > 3 or not 1 == 3 and 'x' == 'x' or 3 > 3
false or true or false
res = (3 > 4 and 4 > 3) or (not 1 == 3 and 'x' == 'x') or 3 > 3
print(res) # 輸出:True
小知識點
隱式布林值
print(1 and 3) # 3
# 數字3為True,算到3列印3
print(1 and 3 or 4) # 3
# 數字3為True,算到3後條件成立則直接列印3