來自:快學Python
歡迎關注 ,專注Python、資料分析、資料挖掘、好玩工具!
近日,Python官網發布了Python3.10.0,

說實話,對于這次的升級,有幾個特性,還真是值得和大家講講,交流學習,文末提供交流群,喜歡點贊支持,歡迎收藏學習,
1. 更友好的錯誤提示
Python 3.10以前,它是這樣提示的,你可能完全不知道哪里有問題,當代碼過多,
print ("Hello"
print ("word")
File ".\test.py", line 2
print ("word")
^
SyntaxError: invalid syntax
對于Python 3.10,它是這樣提示:
File ".\test.py", line 1
print ("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 1
3. 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 ** 2
square(2.5)
# 結果:6.25
新的運算子,也可用作 isinstance() 和 issubclass() 的第二個引數,
# True
isinstance("a", int|str)
# True
issubclass(str, str|int)
技術交流
歡迎轉載、收藏、有所識訓點贊支持一下!

目前開通了技術交流群,群友已超過2000人,添加時最好的備注方式為:來源+興趣方向,方便找到志同道合的朋友
- 方式①、發送如下圖片至微信,長按識別,后臺回復:加群;
- 方式②、添加微信號:dkl88191,備注:來自CSDN
- 方式③、微信搜索公眾號:Python學習與資料挖掘,后臺回復:加群

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/317933.html
標籤:python
