作者:某某白米饭 来源:Python技术 python3。10已经在10月4号发布了,这次更新了错误语法提示对python新手更加友好。好几个新的特性非常的有用,一起来看看吧。更细致的错误语法提示 在调试代码的时候可以精确定位到错误语法的那行,而不是提示SyntaxError的行。1expected{9:1,18:2,19:2,27:3,someothercodefoo()2foo(x,zforzinrange(10),t,w)3try:builddysonsphere()exceptNotEnoughScienceError,NotEnoughResourcesError:4fBlackholes{allblackholes}andrevelations5schwarzschildblackholeNoneschwarschildblackhole 3。9提示的是1someothercodefoo()SyntaxError:invalidsyntax2foo(x,zforzinrange(10),t,w)SyntaxError:Generatorexpressionmustbeparenthesized3exceptNotEnoughScienceError,NotEnoughResourcesError:SyntaxError:invalidsyntax4(allblackholes)SyntaxError:fstring:cantusestarredexpressionhere5schwarschildblackholeNameError:nameschwarschildblackholeisnotdefined 3。10提示的是1expected{9:1,18:2,19:2,27:3,SyntaxError:{wasneverclosed2foo(x,zforzinrange(10),t,w)SyntaxError:Generatorexpressionmustbeparenthesized3exceptNotEnoughScienceError,NotEnoughResourcesError:SyntaxError:multipleexceptiontypesmustbeparenthesized4(allblackholes)SyntaxError:fstring:cannotusestarredexpressionhere5schwarschildblackholeNameError:nameschwarschildblackholeisnotdefined。Didyoumean:schwarzschildblackhole?结构化模式匹配:match。。。case 相当于其他语言的switch。。。casematchsubject:casepattern1:casepattern2:casepattern3:case: 关键字match后跟变量名。如果匹配,则将执行case块内的语句,没有匹配,则执行case块内的语句。1foriin〔1,2,3,4,5,6,7〕:matchi:case1:print(周一)case2:print(周二)case3:print(周三)case4:print(周四)case5:print(周五)case:print(放假了) 结果:1周一周二周三周四周五放假了放假了 再来一个tuple类型的2point(1,2,3)matchpoint:case(0,0,):print(原点)case(0,y,0):print(fY{y})case(x,0,0):print(fX{x})case(x,y,z):print(fX{x},Y{y},Z{z})case:raiseValueError(Notapoint) 结果:2X1,Y2,Z3 可以使用tuple类型,当然也可以使用list类型,类似于:points〔(1,3),(1,2)〕新型联合运算符 以XY的形式引入了新的类型联合运算符。defsquare(number:intfloat):returnnumber2print(square(4))print(square(4。4)) 结果:1619。360000000000003 也可以用作isinstance():一个对象是否是一个已知的类型和issubclass():判断参数class是否是类型参数classinfo的子类的第二个参数。isinstance(5,intstr)isinstance(xxxx,intstr) 结果:TrueTruezip的严格模式 函数zip()增加strict参数,如果设置strictTrue,而传输的参数的长度不相等将会抛出异常。x〔1,2,3,4,5〕y〔1,2,3〕zzip(x,y,strictTrue)print(list(z)) 结果:ValueError:zip()argument2isshorterthanargument1字典增加了mapping属性 dict。items()、dict。keys()、dict。values()分别增加了mapping属性x{name:张三,age:14}keysx。keys()valuesx。values()itemsx。items()print(keys。mapping)print(values。mapping)print(items。mapping)总结 python3。10更新的最有用的就是错误提示了,再也不会看到提示一团迷糊,定位更加的精确,match。。。case终于来了。