Python 3.10刚发布,这5点非常值得学习!
生活随笔
收集整理的這篇文章主要介紹了
Python 3.10刚发布,这5点非常值得学习!
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
正值國慶節期間,Python官網發布了Python3.10.0。
說實話,對于這次的升級,有幾個特性,還真是值得和大家講講。
1. 更友好的錯誤提示
Python 3.10以前,它是這樣提示的,你可能完全不知道哪里有問題,當代碼過多。
print?("Hello" print?("word")File?".\test.py",?line?2print?("word")^ SyntaxError:?invalid?syntax對于Python 3.10,它是這樣提示:
File?".\test.py",?line?1print?("Hello"^ SyntaxError:?'('?was?never?closed給你明確指示錯誤,太香了!
2. zip新增可選參數:嚴格模式
zip新增可選參數strict, 當該選項為True時,傳入zip的兩個可迭代項長度必須相等,否則將拋出 ValueError。
對于Python 3.10以前,沒有該參數,當二者長度不等時,以長度較小的為準。
names?=?["a","b","c","d"] numbers?=?[1,2,3] z?=?zip(names,numbers) for?each?in?z:print(each)結果如下:對于Python 3.10,設置strict為True。
d:測試.py?in?<module>3?numbers?=?[1,2,3]4?z?=?zip(names,numbers,strict=True) ---->?5?for?each?in?z:6?????print(each)ValueError:?zip()?argument?2?is?shorter?than?argument?13. with可以加括號
官方文檔中是這樣寫的:
with?(CtxManager()?as?example):...with?(CtxManager1(),CtxManager2() ):...with?(CtxManager1()?as?example,CtxManager2()):...with?(CtxManager1(),CtxManager2()?as?example):...with?(CtxManager1()?as?example1,CtxManager2()?as?example2 ):...這樣你一定看不懂,如果換成下面這種寫法呢?
with(p1.open(encoding="utf-8")?as?f1,p2.open(encoding="utf-8")?as?f2 ):print(f1.read(),?f2.read(),?sep="\n")就是你現在可以一次性在with中,操作多個文檔了。
4. 結構化模式匹配:match...case...
對,就是其他語言早就支持的的switch-case,Python今天終于提供了支持。
day?=?7 match?day:case?3:print("周三")case?6?|?7:print("周末")case?_?:?print("其它")5. 新型聯合運算符
以 X|Y 的形式引入了新的類型聯合運算符。
def?square(x:?int|float):?return?x?**?2square(2.5)? #?結果:6.25新的運算符,也可用作 isinstance() 和 issubclass() 的第二個參數。
#?True isinstance("a",?int|str)#?True? issubclass(str,?str|int)推薦閱讀
牛逼!Python常用數據類型的基本操作(長文系列第①篇)
牛逼!Python的判斷、循環和各種表達式(長文系列第②篇)
牛逼!Python函數和文件操作(長文系列第③篇)
牛逼!Python錯誤、異常和模塊(長文系列第④篇)
總結
以上是生活随笔為你收集整理的Python 3.10刚发布,这5点非常值得学习!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 致敬!再见了!LayUI !
- 下一篇: 《Python知识手册》,高清pdf免费