speakingphp

phpecho  时间:2021-02-13  阅读:()
CopyrightIBMCorporation2010TrademarksPythonbasicsforPHPdevelopersPage1of10PythonbasicsforPHPdevelopersThomasMyerFebruary09,2010AreyouanexperiencedPHPdeveloperwhoneedstolearnPythonThisarticleapproachestheworldofPythondevelopmentfromaPHPdeveloper'sperspective,translatingfamiliarPHPconcepts,suchasvariables,lists,andfunctions,intotheirPythonequivalents.
You'reaPHPdeveloper.
You'veprobablybeenwritingapplicationsforthepastfiveyears(orlonger),andyou'vebuiltjustabouteverythingimaginable—e-commercesystems,simplecontent-managementsystems,TwitterandFacebookintegrations,andahostofcustomutilities.
You'veprobablymaintainedalotofcode,too—everythingfromsimpledisplaypagestocustomapplicationswithtensofthousandsoflinessomebodyelsewrote.
FrequentlyusedacronymsAjax:AsynchronousJavaScript+XMLXML:ExtensibleMarkupLanguageBecauseyou'vespentsomuchtimeworkinginPHP,it'sdoubtfulthatyou'regoingtojumpshiptoanotherlanguage.
Butyoualsoknowthatstandingstillistheonesurerecipefordisasterinthisfield.
Ifnothingelse,learninganewlanguageisliketravelingoverseas:Yougettoseenewthings,tastenewfood,enjoyadifferentculture,havestimulatingconversationswithdifferentpeople,seeneatstuff,thencomebackhometore-evaluateyourusualsurroundings.
ThisarticlegivesyouabitofexposuretoPython.
Itassumesthatyouhavenoknowledgeofthatprogramminglanguage,sosomeofwhatyoureadheremightseemabitbasic.
ItfocusesoncomparingandcontrastingPythonwithPHP—notbecauseonelanguageisbetterthantheotherbutbecauseofasimpletruth:It'softeneasiertolearnnewthingsbyreferringbacktosomethingyoualreadyknow.
Thegoalofthisarticleissimple:togiveyouaquickworkingknowledgeofPythoninthehopethatyou'lldigalittlefurtheronyourown.
Withluck,you'llseethatPythonisn'treallythatdifferentfromwhatyou'reusedto.
Toextendthetravelmetaphor,youaren'treallygoingtoadistantforeignland,justthecountrynextdoorwhereeveryonespeaksthesamelanguageasyou.
WhatisPythonPythonisclassifiedasa"general-purpose,high-levelprogramminglanguage.
"Itisbestknownforbeingincrediblycleanandeasytoread,anditisoneofthefewlanguagesyou'llencounterinwhichwhitespaceandindentationactuallymatter.
Python'sprincipalauthor,GuidoVandeveloperWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage2of10Rossum,isstillveryactiveinthecommunityandhasbeenbestowedthetongue-in-cheektitleof"BenevolentDictatorforLife.
"OneofthenicethingsaboutPythonisitsflexibilityandcompactness.
Itsupportsobject-oriented,structured,aspect-oriented,andfunctionalprogramming,amongotherapproaches.
Pythonwasdesignedwithasmallcoreandalargesetofextensionlibraries,makingthelanguageextremelycompactandflexible.
Fromasyntaxpointofview,you'llfindPythonveryclean—almostmonasticandZen-likeinitssparsity.
PHPdeveloperswilleitherhaveagreatdealofaffectionforthisapproach,findingreliefinthesyntacticaldiscipline,orfinditrestrictive.
Itjustdependsonyouroutlook.
ThePythoncommunityisclearaboutpromotingthisparticularaesthetic,valuingbeautyandsimplicityovercleverhacks.
ThosePHPdevelopers(likemyself)whocameoutofthePerltradition("There'smorethanonewaytodoit")willbeconfrontedwiththetotaloppositephilosophy("Thereshouldonlybeoneobviouswaytodoit").
Infact,thecommunityhasatermforcodethatfollowsapreferredstyle:pythonic.
TosaythatyourcodeispythonicistosaythatisusesPythonidiomswellorthatyou'reshowingnaturalfluencyinthelanguage.
Thisarticledoesn'tbothertryingtobeaPythonista(orPythoneer),butit'ssomethingyouneedtobeawareofifyouwanttocontinuedownthePythonpath.
JustastherearecertainPHP-ishwaystoworkandPerl-ishwaystodothings,takingonPythonmeansthateventually,youneedtostartthinkinginthatlanguage.
Anotherquicknote:PythonwasuptoV3.
0atthetimeofwriting,butthisarticlefocusesonPythonV2.
6.
PythonV3.
0isnotbackward-compatiblewithearlierversions,anditappearsthatV2.
6istheversionmostcommonlyinuse.
Youarefreetousewhateveryouneed,ofcourse.
HowdoesPythondifferfromPHPGenerallyspeaking,PHPisaWebdevelopmentlanguage.
Yes,ithasacommand-lineinterfaceandcanevenbeusedtodevelopembeddedapplications,butforthemostpart,PHPisforWebdevelopment.
Incontrast,PythonisageneralscriptinglanguagethatcanalsobeusedforWebdevelopment.
Inthisway—andIknowI'llbeyelledatforthis—it'sclosertoPerlthanPHP.
(Ofcourse,inallotherways,itcouldn'tbemoredifferent,really.
Butlet'smoveon.
)PHP'ssyntaxislitteredwithdollarsigns($)andcurlybraces({}),whilePythonismorespareandclean.
PHPhasaswitchanddo.
.
.
whileconstruct;Pythondoesn't.
PHPhastheternaryoperator(foobar:baz)andanenormous(andunwieldy)listoffunctionnames,withallkindsofnamingconventions;you'llfindPythonalotcleaner.
PHPhasanarraytypethatdoublesasasasimplelistandadictionaryorhash;Pythonseparatesthetwo.
Pythonalsohasaconceptofmutabilityandimmutability:atuple,forexample,isanimmutablelist.
Youcreateyourtuple,andyoucan'tchangeitafterthat.
Thisconcepttakesabitofgettingusedto,butit'samarvelouswaytoavoiderrors.
Ofcourse,theonlywaytochangeatupleistocopyit,soifyoufindyourselfmakinglotsofchangestoanimmutableobject,youneedtorethinkyourapproach.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage3of10Asnoted,indentationinPythonhasmeaning:You'lllearnthisthehardwayinyourfirstfewdayswiththelanguage.
Youcanalsocreatefunctionsandmethodswithkeyword-basedarguments—anicebreakfromthestandardpositionalargumentsyouseeinPHP.
Theobject-orientedpuristswillenjoyPython'strueobjectorientation,and"first-class"classesandfunctions.
Ifyou'reworkingwithnon-Englishlanguages,you'lllovePython'sstronginternationalizationandUnicodesupport.
You'llalsolovePython'smulti-threadingcapabilities;thiswasoneofthefeaturesthatoriginallyattractedme.
Allthisbeingsaid,PHPandPythonaresimilartoeachotherinmanyways.
Youwon'thaveanytroublecreatingvariables,looping,usingconditionals,andcreatingfunctions.
Youwon'tevenhavethatmuchtroublecreatingreusablemodules.
Theusercommunitiesforbothlanguagesareactiveandpassionate.
PHP'sinstalledbaseisalotbigger,butthishasmoretodowithitspopularityonhostingserversanditsWebfocusthananythingelse.
OK—enoughwiththeintromaterial.
Let'sgetdowntocases.
WorkingwithPythonListing1presentsabasicPythonscripttogetyoustarted.
Listing1.
AsimplePythonscriptforiinrange(20):print(i)Listing2showstheinevitableresult.
Listing2.
ResultsofListing1012345678910111213141516171819Let'slookatafewthingsbeforegoinganyfurther,startingwithvariables.
VariablesAsyoucansee,therearenospecialcharacterstodenoteavariable.
Thevariableiisjustplaini—nothingspecial.
Therearenospecialcharacters(likesemicolonsandbraces)todenoteadeveloperWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage4of10codeblockoranendofstatement,either;justasimplecolon(:)ontheforline.
AlsonotethattheindentationtellsPythonwhatbelongstotheforloop.
Forexample,thecodeinListing3printsanoteaftereachnumberintheloop.
Listing3.
Addingastatementtoeachloopforiinrange(20):print(i)print('alldone')Incontrast,thecodeinListing4putsanoteattheendoftheloop.
Listing4.
Addingastatementafteraloopforiinrange(20):print(i)print('alldone!
')Now,thefirsttimeIlookedatsomethinglikethat,Ithoughtitwassheermadness.
WhatTrustnewlinesandindentstokeepmycodenotonlystructuredbutrunningBelieveme,afterawhile,you'llgetusedtoit(althoughIhavetoadmitthatIkeepreachingforthatsemicolonkeytofinishastatement).
Ifyou'reworkingwithotherdevelopersonaPythonproject,you'llfindthisreadabilityahugebonus.
You'llhavealotfewermomentsof,"Nowwhatdidthiscleverfellowtrytodohere"InPHP,youassignavaluetoavariableusingthe=operator(seeListing5).
InPython,youusethesameoperator,exceptthatyou'resaidtolabelorpointtoavalue.
Tome,it'sjustassigning,soIdon'tworrytoomuchaboutthejargon.
Listing5.
Creatingvariablesyorkie='Marlowe'#meetourYorkieMarlowe!
mutt='Kafka'#meetourmuttKafkaprint(mutt)#printsKafkaPythonvariablenameconventionsaresimilartoPHP:Youcanonlyuseletters,numbers,andtheunderscorecharacter(_)whencreatingavariablename.
Likewise,thefirstcharacterofavariablenamecan'tbeanumber.
Pythonvariablenamesarecase-sensitive,andyoucan'tusecertainPythonkeywords(suchasif,else,while,def,or,and,not,in,andis,forstarters)asvariablenames.
Nobigsurprisesthere.
Pythonallowsyoutodoanynumberofstring-basedoperations.
MostoftheoperationsinListing6willbefamiliartoyou.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage5of10Listing6.
Commonstring-basedoperationsyorkie='Marlowe'mutt='Kafka'ylen=len(yorkie)#lengthofvariableyorkieprint(ylen)#prints7print(len(yorkie))#doesthesamethinglen(yorkie)#alsodoesthesamething,printisimplicitprint(yorkie.
lower())#lowercasesthestringprint(yorkie.
strip('aeiou'))#removesvowelsfromendofstringprint(mutt.
split('f'))#splits"Kafka"into['Ka','ka']print(mutt.
count('a'))#prints2,thenumberofa'sinstringyorkie.
replace('a','4')#replacea'swith4'sConditionalsYoualreadyknowhowtouseaforloop.
Nowlet'stalkaboutconditionals.
You'llfindthatconditionalsareprettymuchthesameasinPHP:You'llhaveaccesstothefamiliarif/else-typestructuresshowninListing7.
Listing7.
Asimpleconditionaltestyorkie='Marlowe'mutt='Kafka'iflen(yorkie)>len(mutt):print('Theyorkiewins!
')else:print('Themuttwins!
')Youcanalsobuildmorecomplexconditionaltestsusinganif/elif/else(elifbeingtheequivalenttoPHP'selseif),asshowninListing8.
Listing8.
Amorecomplexconditionaltestyorkie='Marlowe'mutt='Kafka'iflen(yorkie)+len(mutt)>15:print('Theyorkieandthemuttwin!
')eliflen(yorkie)+len(mutt)>10:print('Tooclosetotell!
')else:print('Nobodywins!
')Asyoucantell,sofarthere'snothingtooexcitinghere.
It'sallprettymuchwhatyouwouldexpect.
NowlookathowPythonhandleslists;you'llseequiteabitofdifferencebetweenthetwolanguages.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage6of10ListsOnecommontypeoflistiscalledatuple,andasnoted,it'simmutable.
Onceyouloadatuplewithaseriesofvalues,youcan'tchangeit.
Tuplescancontainnumbers,strings,variables,andevenothertuples.
Tuplesare0-indexed,asyou'dexpect;youcanaccessthelastitemusingthe-1index.
Therearealsoquiteafewfunctionsyoucanrunontuples.
Listing9.
Tuplesitems=(1,mutt,'Honda',(1,2,3))printitems[1]#printsKafkaprintitems[-1]#prints(1,2,3)items2=items[0:2]#items2nowcontains(1,'Kafka')thankstosliceoperation'Honda'initems#returnsTRUElen(items)#returns4items.
index('Kafka')#returns1,becauseseconditemmatchesthisindexlocationListsareliketuples,exceptthatthey'remutable.
Onceyoucreatethem,youcanadd,subtract,andupdatethevaluesinthelist.
Insteadofparentheses(()),youusesquarebrackets,asshowninListing10.
Listing10.
Listsgroceries=['ham','spam','eggs']len(groceries)#returns3printgroceries[1]#printsspamforxingroceries:printx.
upper()#printsHAMSPAMEGGSgroceries[2]='bacon'groceries#listisnow['ham','spam','bacon']groceries.
append('eggs')groceries#listisnow['ham','spam','bacon','eggs']groceries.
sort()groceries#listisnow['bacon','eggs','ham','spam']Adictionaryislikeanassociativearrayorhash:Ituseskey-valuepairstostoreandretrieveinformation.
Butinsteadofbracketsorparentheses,youusecurlybraces.
Likelists,dictionariesaremutable,whichmeansyoucanadd,subtract,andupdatevaluesinthem.
Listing11.
Dictionariescolorvalues={'red':1,'blue':2,'green':3,'yellow':4,'orange':5}colorvalues#prints{'blue':2,'orange':5,'green':3,'yellow':4,'red':1}colorvalues['blue']#prints2colorvalues.
keys()#retrievesallkeysasalist:#['blue','orange','green','yellow','red']colorvalues.
pop('blue')#prints2andremovesthebluekey/valuepaircolorvalues#afterpop,wehave:#{'orange':5,'green':3,'yellow':4,'red':1}ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage7of10CreatingasimplescriptinPythonNowthatyou'vehadabitofexposuretoPython,let'sbuildasimplePythonscript.
ThisscriptreadsthenumberofPHPsessionfilesinyourserver's/tmpdirectory,thenwritesasummaryreporttoalogfile.
Inthisscript,you'regoingtolearnhowtoimportmodulesforspecificfunctions,howtoworkwithfiles,andhowtowritetoalogfile.
You'llalsosetanumberofvariablestokeeptrackoftheinformationyou'vegathered.
Listing12showstheentirescript.
Openaneditor,andpastethecodeintoitandsavethefileastmp.
pysomewhereonyoursystem.
Thenrunchmod+xonthatfiletomakeitexecutable(assumingyou'reonaUNIXsystem).
Listing12.
tmp.
py#!
/usr/bin/pythonimportosfromtimeimportstrftimestamp=strftime("%Y-%m-%d%H:%M:%S")logfile='/path/to/your/logfile.
log'path='/path/to/tmp/directory/'files=os.
listdir(path)bytes=0numfiles=0forfinfiles:iff.
startswith('sess_'):info=os.
stat(path+f)numfiles+=1bytes+=info[6]ifnumfiles>1:title='files'else:title='file'string=stampstr(numfiles)+"session"\+title+","+str(bytes)+"bytes\n"file=open(logfile,"a")file.
writelines(string)file.
close()Onthefirstline,youseewhat'scalledthehash-bangline,whichidentifiesthelocationofthePythoninterpreter.
Onmysystem,it'sat/usr/bin/python.
Adjustthistotheneedsofyoursystem.
Thenexttwolinesimportspecificmodulesthathelpyoudoyourjob.
Giventhatthescriptneedstodealwithfoldersandfiles,youneedtoimporttheosmodule,asitcontainsvariousfunctionsandmethodsthathelpyoulistfiles,readfiles,andworkwithfolders.
You'llalsobewritingtoalogfile,soit'sagoodideatoaddatimestamptoentries—hence,theneedforthetimefunctions.
Youwon'tneedallofthem,sojustimportthestrftimefunction.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage8of10Inthenextsixlines,yousetvariables.
Thefirst,calledstamp,containsadatestring.
Youusethestrftimefunctiontocreateatimestampwithaspecificformat—inthiscase,astampthatlookslike2010-01-0312:43:03.
Next,createavariablecalledlogfileandputinapathtoafile(itdoesn'tneedtoexistyet)whereyou'llactuallystorelogfilemessages.
Forsimplicity,Iputlogfilesina/logsfolder,butyoucouldputthemanywhere.
Similarly,youneedavariablecalledpaththatcontainsthepathtoyour/tmpdirectory.
Itcanbeanypathyouwantaslongasyouenditwithatrailingslash(/).
Thenextthreevariablesarejustassimple:afileslistthatcontainsallthefilesandfolderslocatedatyourdesignatedpathandtwovariablescalledbytesandnumfiles.
Bothofthosevariablesaresetto0;thescriptincrementsthosevaluesasitprocessesfiles.
Afterallthatcomestheheartofthescript:asimpleforloopthatprocesseseachfileinthefileslist.
Eachtimethroughtheloop,thescriptevaluatesthefilename.
Ifitbeginswithsess_,thenthescriptrunsos.
stat()onthefiletopulloutdataaboutthefile(suchascreationtime,modifytime,andsizeinbytes),incrementsthenumfilescounter,andaddsthenumberofbytesforthisfiletoarunningtotal.
Whentheloopcompletesitsrun,thescriptcheckstoseewhetherthenumfilesvariablecontainsavaluegreaterthan1.
Ifso,itsetsanewvariable,calledtitle,tofiles;otherwise,thetitleissettothesingularformfile.
Thefinalpartofthescriptissimple:Youcreateafinalvariablecalledstring,andinsidethat,youplaceasinglelineofdatathatstartswiththestampandproceedswithnumfiles(convertedtoastring)andthebytes(alsoconvertedtoastring).
Noticethecontinuationcharacter(\);itallowsthecodetoruntothenextline.
It'sagoodtricktoknowforreadability.
Thenyouusetheopen()functiontoopenthelogfileinappendmode(youwanttokeepaddinglinestothefile,afterall),thewritelines()functiontoaddthestringtothelogfile,andtheclose()functiontoclosethefile.
You'venowcreatedasimplePythonscriptyoucandoanythingwith.
Forexample,youcouldsetacronjobtorunthisscriptonceperhourtohelpyoukeeptrackofhowmanyPHPsessionsarebeingusedaroundtheclock.
YoucouldalsousejQueryorsomeotherJavaScriptframeworktohookthisscriptupusingAjaxtogiveyoualog-filefeed(ifso,you'dneedtousetheprintcommandtoreturndata).
ConclusionAsdevelopers,wespendalotoftimeinvestingourselveswithknowledgeaboutspecificlanguagesandapproaches.
Sometimes,doingsoleadstodebatesaboutthesuperiorityofonelanguageoveranother.
I'veparticipatedinmanyofthesedebates,ashavesomeofyou.
Ihavetoadmitthatmostofthesediscussionstendtofallintothesameoldrut—"anythingyoucandoIcandobetter"—whichdoesn'tserveanygoodpurpose.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage9of10However,onceyoustartlookingcloselyatanotherlanguage,youfindthatmostlanguageshavesimilartools,philosophies,andapproaches.
Learningyourfirstlanguagecanbedifficult,buttakingwhatyouknowandapplyingittoanotherlanguagecanmakethelearningexperiencealoteasier.
Evenifyoudon'treallytakeupthesecondlanguage,youincreaseyourexposuretoideasandmethodsthatwillimproveyourcraft.
Withanyluck,thisarticlehasprovidedyouwithsomeinsightintoPython.
Myhopeisthatyou'llcontinueyourlearningandkeeplookingintothisgreatlanguage.
YoumayneverleavetheworldofPHP(afterall,it'swhatprobablyputsfoodonthetable),butitneverhurtstokeeplearning.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage10of10RelatedtopicsVisitPythonandlearnmoreaboutthelanguage.
ReadthePythondocumentation.
TheBeginner'sGuidetoPythonagoodplacetostartlearningaboutthislanguage.
CheckoutthePythonWikiBook,whichisavailableatnocost.
Read"DiscoverPython"togetafullappreciationforPythonandwhatitcando.
PythonCookbook:CheckoutActiveStateCodetofindPythoncodesamplesthatyoucanemploy.
PHP.
netisthecentralresourceforPHPdevelopers.
Checkoutthe"RecommendedPHPreadinglist.
"BrowseallthePHPcontentondeveloperWorks.
FollowdeveloperWorksonTwitter.
ExpandyourPHPskillsbycheckingoutIBMdeveloperWorks'PHPprojectresources.
UsingadatabasewithPHPCheckouttheZendCoreforIBM,aseamless,out-of-the-box,easy-to-installPHPdevelopmentandproductionenvironmentthatsupportsIBMDB2V9.
VisitdeveloperWorksOpenandcollaboratewithsomeofIBM'sbrightestmindsinacommunitysetting.
Startdevelopingwithproducttrials,freedownloads,andIBMBluemixservices.
CopyrightIBMCorporation2010(www.
ibm.
com/legal/copytrade.
shtml)Trademarks(www.
ibm.
com/developerworks/ibm/trademarks/)

月神科技 国内上新成都高防 全场八折促销续费同价!

月神科技是由江西月神科技有限公司运营的一家自营云产品的IDC服务商,提供香港安畅、香港沙田、美国CERA、成都电信等机房资源,月神科技有自己的用户群和拥有创宇认证,并且也有电商企业将业务架设在月神科技的平台上。本次带来的是全场八折促销,续费同价。并且上新了国内成都高防服务器,单机100G集群1.2T真实防御,上层屏蔽UDP,可定制CC策略。非常适合网站用户。官方网站:https://www.ysi...

Vultr新注册赠送100美元活动截止月底 需要可免费享30天福利

昨天晚上有收到VULTR服务商的邮件,如果我们有清楚的朋友应该知道VULTR对于新注册用户已经这两年的促销活动是有赠送100美元最高余额,不过这个余额有效期是30天,如果我们到期未使用完的话也会失效的。但是对于我们一般用户来说,这个活动还是不错的,只需要注册新账户充值10美金激活账户就可以。而且我们自己充值的余额还是可以继续使用且无有效期的。如果我们有需要申请的话可以参考"2021年最新可用Vul...

BlueHost主机商年中618活动全场低至五折

BlueHost 主机商在以前做外贸网站的时候还是经常会用到的,想必那时候有做外贸网站或者是选择海外主机的时候还是较多会用BlueHost主机商的。只不过这些年云服务器流行且性价比较高,于是大家可选择商家变多,但是BlueHost在外贸主机用户群中可选的还是比较多的。这次年中618活动大促来袭,毕竟BLUEHOST商家目前中文公司设立在上海,等后面有机会也过去看看。他们也会根据我们的国内年中促销发...

phpecho为你推荐
关于上报下学期所需教学软件的通知deduplicationchromecombininggoogle之路android支持ipad支持ipad支持ipad支持ipadtracerouteLinux 下traceroute的工作原理是什么 !fusioncharts如何自定义FusionCharts图表上的工具提示?
网络域名 美国vps vps优惠码 三级域名网站 七牛优惠码 56折 免费网站监控 云图标 华为网络硬盘 qq云端 网游服务器 paypal注册教程 中国电信宽带测速器 超级服务器 百度云加速 西安主机 万网空间 网页加速 小夜博客 linux服务器系统 更多