您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 信息化管理 > 10分钟学会Python
10分钟学会Python[1]2008-04-0923:38原文作者:Poromenos原文链接:LearnPythonin10minutes译者:令狐葱1.准备工作哦,你是要学习Python编程语言但是又苦于找不到一个简洁但是全面的教程么?这个教程就是要试图在10分钟内让你掌握Python。可能它有点不像一个教程,或者说应该介于教程和cheatsheet[可以快速查找的一个简单表单,不知道怎么翻译,译注]之间,所以在这里我只能向你展示一些最基本的概念,旨在让你能够快速入门。显然,如果你真要学习一门编程语言,你需要使用它编码一段时间。我假定你已经有一些熟知的编程知识,因此在这里我就不再讲那些与语言无关的编程知识。教程中的关键字我都让它高亮显示,这样你就可以一眼就看清楚。另外,为了保持教程的简洁,一些知识就只在代码中展示,只有一些简单的注释。2.特性Python是一个强类型(也就是类型都是强制指定的),动态,隐式类型的(即,你不需要声明变量),大小写敏感(var和VAR是两个不同的变量),面向对象(一切皆是对象)的语言。[专业术语翻译有点别扭,译注]3.语法Python没有命令结束标志,并且,使用缩进来区分程序块。块开始的时候缩进开始,块结束的时候缩进结束。声明需要一个:来引领一个缩进块。注释使用#开始并且只占一行。多行注释使用多行字符串。赋值使用等号(=),测试是否相等使用两个等号(==)。可以分别使用+=或者-=来增加或者减少变量值。这在多个数据结构上都适用,包括字符串。你也可以在一行上使用多个变量。举例来说:myvar=3myvar+=2myvar-=1Thisisamultilinecomment.Thefollowinglinesconcatenatethetwostrings.mystring=Hellomystring+=world.printmystringHelloworld.#Thisswapsthevariablesinoneline(!).myvar,mystring=mystring,myvar4.数据类型在Python中可用的数据类型有列表、元组以及字典。在集合库中集合也可用。列表就像是以维数组(但是你还可以有列表的列表),字典就是关联数组(或者叫哈希表),元组就是不可变一维数组(Python中数组可以是任何类型,因此你可以在列表、字典或者元组中混合使用数字、字符串等数据类型)。在所有的数组类型中第一个元素的标号都是0,负数表示从后向前数,-1则表示最后一个元素。变量可以指向函数。用法如下:sample=[1,[another,list],(a,tuple)]mylist=[Listitem1,2,3.14]mylist[0]=Listitem1againmylist[-1]=3.14mydict={Key1:Value1,2:3,pi:3.14}mydict[pi]=3.14mytuple=(1,2,3)myfunction=lenprintmyfunction(mylist)3你可以使用:取到数组的一个范围,:前留空则表示从第一个元素开始,:后留空则表示直到最后一个元素。负值表示从后索引(即-1是最后一个元素)。如下所示:mylist=[Listitem1,2,3.14]printmylist[:]['Listitem1',2,3.1400000000000001]printmylist[0:2]['Listitem1',2]printmylist[-3:-1]['Listitem1',2]printmylist[1:][2,3.14]5.字符串字符串可以使用单引号或者双引号,你可以在使用一个引号的里面嵌套使用另一种引号(也就是说,Hesaid'hello'.是合法的)。多行字符串则使用三引号(单双皆可)。Python还可以让你设置Unicode编码,语法如下:uThisisaunicodestring.使用值填充一个字符串的时候可以使用%(取模运算符)和一个元组。每个%s使用元组中的一个元素替换,从左到右。你还可以使用字典。如下所示:printName:%snNumber:%snString:%s%(myclass.name,3,3*-)Name:PoromenosNumber:3String:---strString=Thisisamultilinestring.#WARNING:Watchoutforthetrailingsin%(key)s.printThis%(verb)sa%(noun)s.%{noun:test,verb:is}Thisisatest.6.流程控制流程控制使用while,if,以及for。没有select[和哪种语言对比?不知道。译注],使用if代替。使用for来列举列表中的元素。要得到一个数字的列表,可以使用range(number)。这些声明的语法如下:rangelist=range(10)printrangelist[0,1,2,3,4,5,6,7,8,9]fornumberinrangelist:#Checkifnumberisoneof#thenumbersinthetuple.ifnumberin(3,4,7,9):#Breakterminatesaforwithout#executingtheelseclause.breakelse:#Continuestartsthenextiteration#oftheloop.It'sratheruselesshere,#asit'sthelaststatementoftheloop.continueelse:#Theelseclauseisoptionalandis#executedonlyiftheloopdidn'tbreak.pass#Donothingifrangelist[1]==2:printTheseconditem(listsare0-based)is2elifrangelist[1]==3:printTheseconditem(listsare0-based)is3else:printDunnowhilerangelist[1]==1:pass7.函数函数使用def关键字。可选参数在必须参数之后出现,并且可以被赋一默认值。对命名参数而言,参数名参数名被赋一个值。函数可以返回一个元组(打开元组你就可以实现返回多个值)。Lanbda函数是个特例,它由一个表达式构成。参数使用引用传递,但是可变类型(元组,列表,数字,字符串等等)不能被改变。举例如下:#arg2andarg3areoptional,theyhavedefaultvalues#ifoneisnotpassed(100andtest,respectively).defmyfunction(arg1,arg2=100,arg3=test):returnarg3,arg2,arg1ret1,ret2,ret3=myfunction(Argument1,arg3=Namedargument)#Usingprintwithmultiplevaluesprintsthemall,separatedbyaspace.printret1,ret2,ret3Namedargument100Argument1#Sameasdeff(x):returnx+1functionvar=lambdax:x+1printfunctionvar(1)28.类Python部分支持类的多重继承。私有变量和方法可以使用至少两个_开始并且至少一个_结束来声明,比如__spam(这只是约定,语言中并没有强制规定)。我们可以给类的实例赋任意的变量。请看下例:classMyClass:common=10def__init__(self):self.myvariable=3defmyfunction(self,arg1,arg2):returnself.myvariable#Thisistheclassinstantiationclassinstance=MyClass()classinstance.myfunction(1,2)3#Thisvariableissharedbyallclasses.classinstance2=MyClass()classinstance.common10classinstance2.common10#Notehowweusetheclassname#insteadoftheinstance.MyClass.common=30classinstance.common30classinstance2.common30#Thiswillnotupdatethevariableontheclass,#insteaditwillcreateanewoneontheclass#instanceandassignthevaluetothat.classinstance.common=10classinstance.common10classinstance2.common30MyClass.common=50#Thishasnotchanged,becausecommonis#nowaninstancevariable.classinstance.common10classinstance2.common50#ThisclassinheritsfromMyClass.Multiple#inheritanceisdeclaredas:#classOtherClass(MyClass1,MyClass2,MyClassN)classOtherClass(MyClass):def__init__(self,arg1):self.myvariable=3printarg1classinstance=OtherClass(hello)helloclassinstance.myfunction(1,2)3#Thisclassdoesn'thavea.testmember,but#wecanaddonetotheinstanceanyway.Note#thatthiswillonlybeamemberofclassinstance.classinstance.test=109.异常处理Python中的异常处理使用try-except[exceptionname]程序块:defsomefunction():try:#Divisionbyzeroraisesanexception10/0exceptZeroDivisionError:printOops,invalid.fnExcept()Oops,invalid.10.包的导入使用import[libname]导入外部包,你也可以为单独的函数使用from[libname]import[funcname]这种形式来导入。下面是一个例子:importrandomfromtimeimportclockrandomint=random.randint(1,100)printrandomint6411.文件I/OPython有一个很大的内建库数组来处理文件的读写。下面的例子展示如何使用Python的文件I/O来序列化(使用pickle把数据结构转换成字符串)。importpicklemylist=[This,is,4,13327]#OpenthefileC:binary.datforwriting.Theletterrbeforethe#filenamestringisusedtopreventbackslashescaping.myfile=fi
本文标题:10分钟学会Python
链接地址:https://www.777doc.com/doc-4210158 .html