




已阅读5页,还剩29页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
PythonCrashCourseIntro,scripts,BachelorsV1.0dd09-12-2014Hour5,WhyPython?,Modernscriptinglanguages:Python,Perl,Ruby,IDL,Matlab,High-levelInteractiveinterpreterEaseofuseSpeedofdevelopmentEncouragesscripting,ratherthanone-offanalysisPermanentrecordRepeatability,Whynotpython?,IfyouwantfastestpossibleperformanceHighlyparallelcodeNeedlow-levelcontrol,WhyPythonisgreat,DesignedtobeeasytolearnanduseclearsyntaxWelldocumentedPowerful,exible,fully-featuredprogramminglanguageBatteriesincludedComprehensivescientictoolsFastInterpreter,introspectionRunseverywhereCompletelyfreeYoualreadyhaveit,WhylearnPython?,LessstressGetmoresciencedoneWidelyusedandgrowingpopularityThroughoutacademiaandindustryNASA,AstraZeneca,Google,IndustrialLightmostrecentroutinesinPytho,Pythoninphysics,CERNPyROOT(researchengineforhighenergyphysics)PyMad(simulateparticleaccelerators)ComputationalphysicsALPS(AlgorithmsandLibrariesforPhysicsSimulations),Introductiontolanguage-start,LinuxAtcommandline:pythonmyscript.pyWithscript:chmod,#!/usr/bin/envpythonAtpythonprompt:execle(somele.py)Atipythonprompt:%runsomele.py,Introductiontolanguage-start,WindowsFilesthathavetheextension.pyareknownasPythonscripts.InWindowsandMacOS,thesefileswillappeartobeclickable,i.e.willappeartobefilesthatyoucanopenbyclickingthemwiththemouse.Itisnotrecommendedthatyouopenthesefilesbyclickingonthem.Why?Becausequiteoftentheresultcanbeunpredictable.Instead,startIDLEandopenPythonscriptsinsideanIDLEsession.,Introductiontolanguage-startup,pczaal2:pythonPython2.7.5(default,Nov32014,14:26:24)GCC4.8.320140911(RedHat4.8.3-7)onlinux2Typehelp,copyright,creditsorlicenseformoreinformation.2+24#Thisisacomment.2+242+2.0#andacommentonthesamelineascode4.0(50-5*6)/45width=20#assignment,notypedeclarationheight=5*9width*height900x=y=z=0#zerox,yandzy0nTraceback(mostrecentcalllast):File,line1,inNameError:namenisnotdefined,Introductiontolanguage-scripts,CanwriteinatexteditorandcopyandpasteintointerpreterCansaveandexecutefromcommandline:$pythontest.pyCansaveanduseinteractivelyinfuturesessions(import),2+2#Thisisacomment2+22+2.0#andacommentonthesamelineascode(50-5*6)/4width=20#assignment,notypedeclarationheight=5*9width*heightx=y=z=0#zerox,yandzy,Pythonscript,Startaneditorandtypesomepythoncommands.Saveyourfileas:myfirst.pyOntheUnixcommandlinetype:pythonmyfirst.pyWewanttobeabletostarttheprogrambyonlytypingitsname.Tomakeitexecutableusechmodu+xmyfirst.pyorchmod+xmyfirst.pyifyouwanttoalloweverybodyonthesystemtoexecuteyourprogramRunitwith:./myfirst.pyThedotslashpartisnecessarytoforceexecutionifyourcurrentdirectoryisnotincludedinthesettingsforyourpath!Ifyoutypecommandecho$pathonthecommandline,thenalistisdisplayedwithdirectorieswiththepathstothesedirectoriesincluded.Ifyoutypethenameofanexecutablefileonthecommandlinethenallthedirectoriesinthelistarevisitedtolookforthewantedexecutable.Ifthenameisfound,itwillbeexecuted.Ifnot,thenyougetawarning.Nowwegetanerrormessage.RememberthatwecreatedascriptandthefirstlineofascriptshouldcontainthesocalledshebanglinewhichdefinesthepathtotheapplicationthathastoexecutethescriptAddinyourscriptashebanglineasthefirstline:#!/usr/bin/envpythonRunitwith:./myfirst.pyItshouldgiveyoutherightanswer.,Introductiontolanguage-numbers,10+31310-3710*33010/3310/3310%3110*3100010+3*5#*,/then+,-25(10+3)*565-1*2#-(1*2)-1,10.0+3.013.010.0-3.07.010.0*330.010.0/33.333333333333333510.0/33.010.0%3.01.010.0*31000.04.2+3.147.33999999999999994.2*3.1413.188000000000001,Introductiontolanguage-numbers,Integerdivisionisweird!IntegerdivisiontruncatesFloatingpointdivisionproducesfloatingpointnumbers10/259/2499/100010.0/2.05.099.0/100.00.99,MixingIntegerandFloatingWhenyouperformanoperationwhereoneoperandisanintegerandtheotheroperandisafloatingpointtheresultisafloatingpointTheintegerisconvertedtoafloatingpointbeforetheoperation99/100099/100.00.9999.0/1000.991+2*3/4.0-5-2.5,ArithmeticOperators,Assumevariableaholds10andvariablebholds20then:,ArithmeticOperatorsPrecedence,HighestprecedenceruletolowestprecedenceruleParenthesisarealwaysrespectedExponentiation(raisetoapower)Multiplication,Division,andRemainderAdditionandSubtractionLefttoright,ParenthesisPowerMultiplicationAdditionLefttoRight,1+2*3/4*51+8/4*51+2*51+1011,Numericaltypes,Integers:20-471107,022#Octaltuple0 x9,0 xa,0XF#Hexadecimaltuple17+4#Expression0 xa-223*(2+3)#Power7/2,7/-2#Intdivisionfrom_future_importdivision7/2,Floats:2.3-4.0.1,.12.99E10,6.62607e-27,-1e101.7+.417.+47./2.,7./2,7/2.,Longintegers:2*10002L,3l111111111111111111111111111111111111111111float(2),float(2*1000)int(2.3),int(-2.3)int(2*1000),long(2),str(2),Complexnumbers:2.+3j,2-3J#complexliteralsj#willnotwork1J#butthiswillcomplex(1,2)#Watchoperatorprecedence:1+1j*2,(1+1j)*2(2.+3j).real,(2+3j).imagtype(2-3j),Introductiontolanguage-variables,x=2#Assignvariablex#Displayx+3#Usevariabley=x+3#Newvariablex=x+1#Assignnewvaluex+=1#Shorthand;butnox+x=12.3+98.7j#Changetypex*=2j,Sometricks:x,y=2,3x,y=y,x#Notemporaryvariablesneededx=y=z=1,xy,Xy=2,3#Casesensitive9x=2#Notallowed,mustbeginw.letterx9=2#ok_x=2#ok,butspecialif=2#mustnotbekeyword,Reservedkeywords:anddelfromnotwhileaselifglobalorwithassertelseifpassyieldbreakexceptimportprintclassexecinraisecontinuenallyisreturndefforlambdatryNoneaswith,Introductiontolanguage-type,eee=hello+thereeee=eee+1Traceback(mostrecentcalllast):File,line1,inTypeError:cannotconcatenatestrandintobjectstype(eee)type(hello)type(1),Pythonknowswhat“type”everythingisSomeoperationsareprohibitedYoucannot“add1”toastringWecanaskPythonwhattypesomethingisbyusingthetype()function.,AssignmentOperators,Assumevariableaholds10andvariablebholds20then:,0.6,AssignmentOperators,x,Rightsideisanexpression.Onceexpressionisevaluated,theresultisplacedin(assignedto)X.,0.93,Avariableisamemorylocationusedtostoreavalue(0.6),x=3.9*x*(1-x),0.6,0.4,0.6,0.60.93,AssignmentOperators,x,Rightsideisanexpression.Onceexpressionisevaluated,theresultisplacedin(assignedto)thevariableontheleftside(i.e.x).,0.93,Avariableisamemorylocationusedtostoreavalue.Thevaluestoredinavariablecanbeupdatedbyreplacingtheoldvalue(0.6)withanewvalue(0.93).,x=3.9*x*(1-x),Pythonenvironment,PYTHONSTARTUPPersonalstartupfiledefinedinstartupfile:setenvPYTHONSTARTUP/home/personal/mystartup.pyallcodeinstartupfilewillbeexecuteduponstartPYTHONPATHtellsthePythoninterpreterwheretolocatethemodulefilesyouimportintoaprogramsetenvPYTHONPATH“/usr/lib64/python2.7/site-packages:/home/personal/python/site-packages”,$ls/usr/lib64/python2.7/site-packagesabrt_exception_handler.pyabrt_exception_handler.pycabrt_exception_handler.pyoabrt.pthacutilmodule.so*audit.pyaudit.pycaudit.pyo_audit.so*auparse.so*Avogadro.so*basemap-1.0.6-py2.7.egg-info_blueman.so*Brlapi-0.5.6-py2.7.egg-infobrlapi.so*cairo/.,ipython,WhatisitinteractiveshellforthePythonprogramminglanguagethatoffersenhancedintrospection,additionalshellsyntax,tabcompletionandrichhistory.WhydefaultinteractivePythonshellcansometimesfeeltobasicgivesyouallthatyougetinthebasicinterpreterbutwithalotextra(linenumbers,advancedediting,morefunctions,helpfunctionsetc),Python2.7.5(default,Nov32014,14:26:24)Typecopyright,creditsorlicenseformoreinformation.IPython1.1.0-AnenhancedInteractivePython.?-IntroductionandoverviewofIPythonsfeatures.%quickref-Quickreference.help-Pythonsownhelpsystem.object?-Detailsaboutobject,useobject?forextradetails.From.ipythonstarupenvIn1:,Pythonenvironment,PYTHONSTARTUPPersonalstartupfiledefinedinstartupfile:setenvPYTHONSTARTUP/home/personal/mystartup.pyallcodeinstartupfilewillbeexecuteduponstartProfile/.ipythondirectorystructureallscriptsin.ipython/profile_default/startupareexecuteduponstartnewprofilecanbecreatedusing:$ipythonprofilecreateprofile_nameandused:$ipython-profile=profile_name,ipython,TABcompletionespeciallyforattributes,isaconvenientwaytoexplorethestructureofanyobjectyouredealingwithbesidesPythonobjectsandkeywords,tabcompletionalsoworksonfileanddirectorynames,In1:fromsysimportstdstderrstdinstdoutIn1:fromurllib2importurlurl2pathnameurlopenurlparse,In4:x._x._abs_x._hash_x._reduce_x._add_x._init_x._reduce_ex_x._class_x._int_x._repr_x._coerce_x._le_x._rfloordiv_x._delattr_x._long_x._rmod_x._div_x._lt_x._rmul_x._divmod_x._mod_x._rpow_x._doc_x._mul_x._rsub_x._eq_x._ne_x._rtruediv_x._float_x._neg_x._setattr_x._floordiv_x._new_x._setformat_x._format_x._nonzero_x._sizeof_x._ge_x._pos_x._str_x._getattribute_x._pow_x._sub_x._getformat_x._radd_x._subclasshook_x._getnewargs_x._rdiv_x._truediv_x._gt_x._rdivmod_x._trunc_,ipython,Magicbuiltincommands%quickref,In57:lsmagicAvailablelinemagics:%alias%alias_magic%autocall%autoindent%automagic%bookmark%cd%colors%config%cpaste%debug%dhist%dirs%doctest_mode%ed%edit%env%gui%hist%history%install_default_config%install_ext%install_profiles%killbgscripts%load%load_ext%loadpy%logoff%logon%logstart%logstate%logstop%lsmagic%macro%magic%notebook%page%paste%pastebin%pdb%pdef%pdoc%pfile%pinfo%pinfo2%popd%pprint%precision%profile%prun%psearch%psource%pushd%pwd%pycat%pylab%quickref%recall%rehashx%reload_ext%rep%rerun%reset%reset_selective%run%save%sc%store%sx%system%tb%time%timeit%unalias%unload_ext%who%who_ls%whos%xdel%xmodeAvailablecellmagics:%!%bash%capture%file%perl%prun%ruby%script%sh%sx%system%timeitAutomagicisON,%prefixISNOTneededforlinemagics.,IPython-AnenhancedInteractivePython-QuickReferenceCard=obj?,obj?:Gethelp,ormorehelpforobject(alsoworksas?obj,?obj).?foo.*abc*:Listnamesinfoocontainingabcinthem.%magic:InformationaboutIPythonsmagic%functions.Magicfunctionsareprefixedby%or%,andtypicallytaketheirargumentswithoutparentheses,quotesorevencommasforconvenience.Linemagicstakeasingle%andcellmagicsareprefixedwithtwo%.Examplemagicfunctioncalls:%aliasdls-F:disnowanaliasforls-Faliasdls-F:Worksifaliasnotapythonnamealist=%alias:Getlistofaliasestoalistcd/usr/share:Obvious.cd-tochoosefromvisiteddirs.%cd?:SeehelpANDsourceformagic%cd%timeitx=10:timethex=10statementwithhighprecision.%timeitx=2*100 x*100:timex*100withasetupofx=2*100;setupcodeisnotcounted.Thisisanexampleofacellmagic.,ipython,Inputcachingsysteminputissavedandcanberetrievedasvariables_i,previous,_ii,nextprevious,_iiietc.MacrosmacrosaregreatforexecutingthesamecodeoverandoverassociateanamewithasectionofPythoncodesothecodecanberunlaterbyreferringtothename,In1:a=2In2:b=3In3:c=a+bIn4:printc5In5:%macroxxx1-24Macroxxxcreated.Toexecute,typeitsname(withoutquotes).=Macrocontents:=a=2b=3printcIn6:xxx5,In1:a=2In2:b=3In3:c=a+bIn4:_iiOut4:ub=3In5:_ih1Out5:ua=2In6:In3Out6:uc=a+bIn7:printcOut6:5In8:exec_ih7Out8:5,ipython,Usefulhelpcommands%resetresetstheinteractiveenvironment%histallowsyoutoseeanypartofyourinputhistory%hist-gsomestringSearch(grep)throughyourhistorybytypingIn55:hist-gmath19:importmath55:hist-gmath%pasteusetextthatyouhaveintheclipboard,forexampleifyouhavecopiedcodewithCtrl+C.Thecommandcleansupcer
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 设施农种植管理办法
- 规范生物质管理办法
- 中华寿桃病虫管理办法
- 装修人员平台管理办法
- 《流动资金管理办法》
- 装修预算公司管理办法
- 中山公园摆摊管理办法
- 2025年环形磁体合作协议书
- 老虎潭水库管理办法
- 《医学装备管理办法》
- 海门市小升初历年数学试卷
- 2025-2030中国天然气汽车行业发展分析及发展前景与趋势预测研究报告
- 2025年辅警招聘考试试题库附完整答案(历年真题)
- 痔疮病人护理课件
- 2025至2030中国5G毫米波设备行业项目调研及市场前景预测评估报告
- 现代教育技术说课
- 部编版五年级上册语文单元教学计划
- 产品经理绩效管理制度
- 2025年烟台市中考历史试卷真题(含答案)
- 2025四川产业振兴基金投资集团有限公司招聘12人笔试参考题库附带答案详解析集合
- 风湿免疫病患者结核病诊治及预防实践指南(2025版)解读课件
评论
0/150
提交评论