3.8【2019-10】
🌟新增
更多准确的类型
此时,Python的键入系统已经相当成熟。但是,在Python 3.8中,添加了一些新功能typing以允许更精确的键入:
海象运算符 :=
它的英文原名叫 Assignment Expressions
,翻译过来也就是 赋值表达式
,不过现在大家更普遍地称之为海象运算符,就是因为它长得真的太像海象了。
应用场景:
- if/else 赋值优化
# 使用前
age = 20
if age > 18:
print("已经成年了")
#使用后
if (age:= 20) > 18:
print("已经成年了")
- while 判断优化
file = open("demo.txt", "r")
while True:
line = file.readline()
if not line:
break
print(line.strip())
#使用后
file = open("demo.txt", "r")
while (line := file.readline()):
print(line.strip())
while True:
p = input("Enter the password: ")
if p == "youpassword":
break
#使用后
while (p := input("Enter the password: ")) != "youpassword":
continue
- 优化列表推导
fat_bmis = [bmi for m in members if (bmi := get_bmi(m)) > 24]