6.運算式—Python3.12.7說明文件

ThischapterexplainsthemeaningoftheelementsofexpressionsinPython.

SyntaxNotes:Inthisandthefollowingchapters,extendedBNFnotationwillbeusedtodescribesyntax,notlexicalanalysis.When(onealternativeof)asyntaxrulehastheform

name::=othernameandnosemanticsaregiven,thesemanticsofthisformofnamearethesameasforothername.

Whenadescriptionofanarithmeticoperatorbelowusesthephrase"thenumericargumentsareconvertedtoacommontype",thismeansthattheoperatorimplementationforbuilt-intypesworksasfollows:

Someadditionalrulesapplyforcertainoperators(e.g.,astringasaleftargumenttothe'%'operator).Extensionsmustdefinetheirownconversionbehavior.

Atomsarethemostbasicelementsofexpressions.Thesimplestatomsareidentifiersorliterals.Formsenclosedinparentheses,bracketsorbracesarealsocategorizedsyntacticallyasatoms.Thesyntaxforatomsis:

Whenanidentifierthattextuallyoccursinaclassdefinitionbeginswithtwoormoreunderscorecharactersanddoesnotendintwoormoreunderscores,itisconsideredaprivatenameofthatclass.

也參考

Moreprecisely,privatenamesaretransformedtoalongerformbeforecodeisgeneratedforthem.Ifthetransformednameislongerthan255characters,implementation-definedtruncationmayhappen.

Thetransformationisindependentofthesyntacticalcontextinwhichtheidentifierisusedbutonlythefollowingprivateidentifiersaremangled:

Thetransformationruleisdefinedasfollows:

Pythonsupportsstringandbytesliteralsandvariousnumericliterals:

Allliteralscorrespondtoimmutabledatatypes,andhencetheobject'sidentityislessimportantthanitsvalue.Multipleevaluationsofliteralswiththesamevalue(eitherthesameoccurrenceintheprogramtextoradifferentoccurrence)mayobtainthesameobjectoradifferentobjectwiththesamevalue.

Aparenthesizedformisanoptionalexpressionlistenclosedinparentheses:

Anemptypairofparenthesesyieldsanemptytupleobject.Sincetuplesareimmutable,thesamerulesasforliteralsapply(i.e.,twooccurrencesoftheemptytuplemayormaynotyieldthesameobject).

Notethattuplesarenotformedbytheparentheses,butratherbyuseofthecomma.Theexceptionistheemptytuple,forwhichparenthesesarerequired---allowingunparenthesized"nothing"inexpressionswouldcauseambiguitiesandallowcommontypostopassuncaught.

Forconstructingalist,asetoradictionaryPythonprovidesspecialsyntaxcalled"displays",eachofthemintwoflavors:

Commonsyntaxelementsforcomprehensionsare:

However,asidefromtheiterableexpressionintheleftmostforclause,thecomprehensionisexecutedinaseparateimplicitlynestedscope.Thisensuresthatnamesassignedtointhetargetlistdon't"leak"intotheenclosingscope.

Theiterableexpressionintheleftmostforclauseisevaluateddirectlyintheenclosingscopeandthenpassedasanargumenttotheimplicitlynestedscope.Subsequentforclausesandanyfilterconditionintheleftmostforclausecannotbeevaluatedintheenclosingscopeastheymaydependonthevaluesobtainedfromtheleftmostiterable.Forexample:[x*yforxinrange(10)foryinrange(x,x+10)].

Toensurethecomprehensionalwaysresultsinacontaineroftheappropriatetype,yieldandyieldfromexpressionsareprohibitedintheimplicitlynestedscope.

在3.6版被加入:Asynchronouscomprehensionswereintroduced.

在3.8版的變更:yieldandyieldfromprohibitedintheimplicitlynestedscope.

在3.11版的變更:Asynchronouscomprehensionsarenowallowedinsidecomprehensionsinasynchronousfunctions.Outercomprehensionsimplicitlybecomeasynchronous.

Alistdisplayisapossiblyemptyseriesofexpressionsenclosedinsquarebrackets:

Asetdisplayisdenotedbycurlybracesanddistinguishablefromdictionarydisplaysbythelackofcolonsseparatingkeysandvalues:

Anemptysetcannotbeconstructedwith{};thisliteralconstructsanemptydictionary.

Adictionarydisplayisapossiblyemptyseriesofdictitems(key/valuepairs)enclosedincurlybraces:

Ifacomma-separatedsequenceofdictitemsisgiven,theyareevaluatedfromlefttorighttodefinetheentriesofthedictionary:eachkeyobjectisusedasakeyintothedictionarytostorethecorrespondingvalue.Thismeansthatyoucanspecifythesamekeymultipletimesinthedictitemlist,andthefinaldictionary'svalueforthatkeywillbethelastonegiven.

Adictcomprehension,incontrasttolistandsetcomprehensions,needstwoexpressionsseparatedwithacolonfollowedbytheusual"for"and"if"clauses.Whenthecomprehensionisrun,theresultingkeyandvalueelementsareinsertedinthenewdictionaryintheordertheyareproduced.

Ageneratorexpressionisacompactgeneratornotationinparentheses:

Toavoidinterferingwiththeexpectedoperationofthegeneratorexpressionitself,yieldandyieldfromexpressionsareprohibitedintheimplicitlydefinedgenerator.

在3.6版被加入:Asynchronousgeneratorexpressionswereintroduced.

defgen():#definesageneratorfunctionyield123asyncdefagen():#definesanasynchronousgeneratorfunctionyield123Duetotheirsideeffectsonthecontainingscope,yieldexpressionsarenotpermittedaspartoftheimplicitlydefinedscopesusedtoimplementcomprehensionsandgeneratorexpressions.

在3.8版的變更:Yieldexpressionsprohibitedintheimplicitlynestedscopesusedtoimplementcomprehensionsandgeneratorexpressions.

Allofthismakesgeneratorfunctionsquitesimilartocoroutines;theyyieldmultipletimes,theyhavemorethanoneentrypointandtheirexecutioncanbesuspended.Theonlydifferenceisthatageneratorfunctioncannotcontrolwheretheexecutionshouldcontinueafterityields;thecontrolisalwaystransferredtothegenerator'scaller.

在3.3版的變更:Addedyieldfromtodelegatecontrolflowtoasubiterator.

Theparenthesesmaybeomittedwhentheyieldexpressionisthesoleexpressionontherighthandsideofanassignmentstatement.

TheproposaltoenhancetheAPIandsyntaxofgenerators,makingthemusableassimplecoroutines.

Thissubsectiondescribesthemethodsofageneratoriterator.Theycanbeusedtocontroltheexecutionofageneratorfunction.

在3.12版的變更:Thesecondsignature(type[,value[,traceback]])isdeprecatedandmayberemovedinafutureversionofPython.

Hereisasimpleexamplethatdemonstratesthebehaviorofgeneratorsandgeneratorfunctions:

Theexpressionyieldfromisasyntaxerrorwhenusedinanasynchronousgeneratorfunction.

Thissubsectiondescribesthemethodsofanasynchronousgeneratoriterator,whichareusedtocontroltheexecutionofageneratorfunction.

Primariesrepresentthemosttightlyboundoperationsofthelanguage.Theirsyntaxis:

Aconsequenceofthisisthatalthoughthe*expressionsyntaxmayappearafterexplicitkeywordarguments,itisprocessedbeforethekeywordarguments(andany**expressionarguments--seebelow).So:

Formalparametersusingthesyntax*identifieror**identifiercannotbeusedaspositionalargumentslotsoraskeywordargumentnames.

Acallalwaysreturnssomevalue,possiblyNone,unlessitraisesanexception.Howthisvalueiscomputeddependsonthetypeofthecallableobject.

Ifitis---

Anewinstanceofthatclassisreturned.

Thecorrespondinguser-definedfunctioniscalled,withanargumentlistthatisonelongerthantheargumentlistofthecall:theinstancebecomesthefirstargument.

Thepoweroperatorbindsmoretightlythanunaryoperatorsonitsleft;itbindslesstightlythanunaryoperatorsonitsright.Thesyntaxis:

Forintoperands,theresulthasthesametypeastheoperandsunlessthesecondargumentisnegative;inthatcase,allargumentsareconvertedtofloatandafloatresultisdelivered.Forexample,10**2returns100,but10**-2returns0.01.

Allunaryarithmeticandbitwiseoperationshavethesamepriority:

Thebinaryarithmeticoperationshavetheconventionalprioritylevels.Notethatsomeoftheseoperationsalsoapplytocertainnon-numerictypes.Apartfromthepoweroperator,thereareonlytwolevels,oneformultiplicativeoperatorsandoneforadditiveoperators:

在3.5版被加入.

The+(addition)operatoryieldsthesumofitsarguments.Theargumentsmusteitherbothbenumbersorbothbesequencesofthesametype.Intheformercase,thenumbersareconvertedtoacommontypeandthenaddedtogether.Inthelattercase,thesequencesareconcatenated.

The-(subtraction)operatoryieldsthedifferenceofitsarguments.Thenumericargumentsarefirstconvertedtoacommontype.

Theshiftingoperationshavelowerprioritythanthearithmeticoperations:

Arightshiftbynbitsisdefinedasfloordivisionbypow(2,n).Aleftshiftbynbitsisdefinedasmultiplicationwithpow(2,n).

Eachofthethreebitwiseoperationshasadifferentprioritylevel:

UnlikeC,allcomparisonoperationsinPythonhavethesamepriority,whichislowerthanthatofanyarithmetic,shiftingorbitwiseoperation.AlsounlikeC,expressionslikea

Comparisonscanbechainedarbitrarily,e.g.,x

Formally,ifa,b,c,...,y,zareexpressionsandop1,op2,...,opNarecomparisonoperators,thenaop1bop2c...yopNzisequivalenttoaop1bandbop2cand...yopNz,exceptthateachexpressionisevaluatedatmostonce.

Notethataop1bop2cdoesn'timplyanykindofcomparisonbetweenaandc,sothat,e.g.,xzisperfectlylegal(thoughperhapsnotpretty).

Theoperators<,>,==,>=,<=,and!=comparethevaluesoftwoobjects.Theobjectsdonotneedtohavethesametype.

Thedefaultbehaviorforequalitycomparison(==and!=)isbasedontheidentityoftheobjects.Hence,equalitycomparisonofinstanceswiththesameidentityresultsinequality,andequalitycomparisonofinstanceswithdifferentidentitiesresultsininequality.Amotivationforthisdefaultbehavioristhedesirethatallobjectsshouldbereflexive(i.e.xisyimpliesx==y).

Thebehaviorofthedefaultequalitycomparison,thatinstanceswithdifferentidentitiesarealwaysunequal,maybeincontrasttowhattypeswillneedthathaveasensibledefinitionofobjectvalueandvalue-basedequality.Suchtypeswillneedtocustomizetheircomparisonbehavior,andinfact,anumberofbuilt-intypeshavedonethat.

Thefollowinglistdescribesthecomparisonbehaviorofthemostimportantbuilt-intypes.

User-definedclassesthatcustomizetheircomparisonbehaviorshouldfollowsomeconsistencyrules,ifpossible:

Pythondoesnotenforcetheseconsistencyrules.Infact,thenot-a-numbervaluesareanexamplefornotfollowingtheserules.

Forthestringandbytestypes,xinyisTrueifandonlyifxisasubstringofy.Anequivalenttestisy.find(x)!=-1.Emptystringsarealwaysconsideredtobeasubstringofanyotherstring,so""in"abc"willreturnTrue.

Theexpressionxandyfirstevaluatesx;ifxisfalse,itsvalueisreturned;otherwise,yisevaluatedandtheresultingvalueisreturned.

Theexpressionxoryfirstevaluatesx;ifxistrue,itsvalueisreturned;otherwise,yisevaluatedandtheresultingvalueisreturned.

Onecommonusecaseiswhenhandlingmatchedregularexpressions:

ifmatching:=pattern.search(data):do_something(matching)Or,whenprocessingafilestreaminchunks:

whilechunk:=file.read(9000):process(chunk)Assignmentexpressionsmustbesurroundedbyparentheseswhenusedasexpressionstatementsandwhenusedassub-expressionsinslicing,conditional,lambda,keyword-argument,andcomprehension-ifexpressionsandinassert,with,andassignmentstatements.Inallotherplaceswheretheycanbeused,parenthesesarenotrequired,includinginifandwhilestatements.

TheexpressionxifCelseyfirstevaluatesthecondition,Cratherthanx.IfCistrue,xisevaluatedanditsvalueisreturned;otherwise,yisevaluatedanditsvalueisreturned.

Atrailingcommaisrequiredonlytocreateaone-itemtuple,suchas1,;itisoptionalinallothercases.Asingleexpressionwithoutatrailingcommadoesn'tcreateatuple,butratheryieldsthevalueofthatexpression.(Tocreateanemptytuple,useanemptypairofparentheses:().)

Pythonevaluatesexpressionsfromlefttoright.Noticethatwhileevaluatinganassignment,theright-handsideisevaluatedbeforetheleft-handside.

Inthefollowinglines,expressionswillbeevaluatedinthearithmeticorderoftheirsuffixes:

Operator

描述

(expressions...),

[expressions...],{key:value...},{expressions...}

Bindingorparenthesizedexpression,listdisplay,dictionarydisplay,setdisplay

x[index],x[index:index],x(arguments...),x.attribute

Subscription,slicing,call,attributereference

Awaitexpression

**

+x,-x,~x

Positive,negative,bitwiseNOT

+,-

Additionandsubtraction

<<,>>

Shifts

&

BitwiseAND

^

BitwiseXOR

|

BitwiseOR

Comparisons,includingmembershiptestsandidentitytests

BooleanNOT

BooleanAND

BooleanOR

Conditionalexpression

Lambdaexpression

:=

Assignmentexpression

註解

Ifxisveryclosetoanexactintegermultipleofy,it'spossibleforx//ytobeonelargerthan(x-x%y)//yduetorounding.Insuchcases,Pythonreturnsthelatterresult,inordertopreservethatdivmod(x,y)[0]*y+x%ybeveryclosetox.

TheUnicodestandarddistinguishesbetweencodepoints(e.g.U+0041)andabstractcharacters(e.g."LATINCAPITALLETTERA").WhilemostabstractcharactersinUnicodeareonlyrepresentedusingonecodepoint,thereisanumberofabstractcharactersthatcaninadditionberepresentedusingasequenceofmorethanonecodepoint.Forexample,theabstractcharacter"LATINCAPITALLETTERCWITHCEDILLA"canberepresentedasasingleprecomposedcharacteratcodepositionU+00C7,orasasequenceofabasecharacteratcodepositionU+0043(LATINCAPITALLETTERC),followedbyacombiningcharacteratcodepositionU+0327(COMBININGCEDILLA).

ThecomparisonoperatorsonstringscompareatthelevelofUnicodecodepoints.Thismaybecounter-intuitivetohumans.Forexample,"\u00C7"=="\u0043\u0327"isFalse,eventhoughbothstringsrepresentthesameabstractcharacter"LATINCAPITALLETTERCWITHCEDILLA".

Thepoweroperator**bindslesstightlythananarithmeticorbitwiseunaryoperatoronitsright,thatis,2**-1is0.5.

The%operatorisalsousedforstringformatting;thesameprecedenceapplies.

THE END
1.047Python面试知识点小结51CTO博客047 Python面试知识点小结 一.Python基础 1.Python语言特性: 动态型(运行期确定类型,静态型是编译型确定类型),强类型(不发生隐式转换,弱类型,如PHP,JavaScript就会发生隐患式转换) 2.Python作为后端语言的优缺点: 优点: 胶水语言,轮子多,应用广泛;语言灵活,生产力高https://blog.51cto.com/u_15127611/4740641
2.python基础知识汇总python期末个人总结资源python基础知识汇总 导航 登录 登录后您可以: 免费复制代码 关注/点赞/评论/收藏 下载海量资源 写文章/发动态/加入社区 立即登录 会员中心 消息 创作中心 学习中心成长任务 发布 版权申诉 python 基础知识 入门教程 5星· 超过95%的资源102 浏览量2021-01-02上传2.28MBPDFhttps://download.csdn.net/download/bala5569/14010591
3.一张图汇总Python基础知识一张图汇总Python基础知识 今天用一张思维导图汇总了Python基础知识,与大家分享。第一张图为总图,之后为总图的局部。 总图 局部1 局部2 局部3https://www.jianshu.com/p/e692bf226ad4
4.Python基础知识点总结.pdfPythonPython基础知识点总结.pdf 39页内容提供方:▄︻︼━┭──加勒比海盗 大小:3.12 MB 字数:约4.35万字 发布时间:2022-04-14发布于甘肃 浏览人气:130 下载次数:仅上传者可见 收藏次数:0 需要金币:*** 金币 (10金币=人民币1元)Python基础知识点总结.pdf 关闭预览 想预览更多内容,点击免费在线预https://max.book118.com/html/2022/0413/6150230023004134.shtm
5.python编程入门基础知识python编程入门基础知识 Python现在是越来越火爆,不仅是风靡世界,还直接进入了中小学生的课堂。所以有越来越多的人想要尝试编程了。 想到以前当我第一次用代码打出“Hello, world”的时候,那种兴奋激动之情,真的是难以言表。 不过很多同学在刚入门的时候,可能还是对Python有一种距离感,毕竟平时看到的编程代码可能都https://www.bunian.cn/17652.html
6.python入门基础知识len函数Python作为当下主流的后端编程语言之一,越来越被更多的企业广泛应用,Python行业广阔的发展前景吸引了很多人想要投身其中,通过Python课程培训机构学习专业的开发技能,今天八维职业学校和大家一起来看看python入门基础知识len函数,希望有助于大家学习,Python中的len函数是一个非常常用的函数,它用于返回一个对象的长度或元素的个https://www.bwie.com/index.php/jsgh/150.html