人生苦短我用python python如何快速入门?
假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手册(CheatSheet)之间,因此只会包含一些基本概念。很显然,如果你希望真正学好一门语言,你还是需要亲自动手实践的。在此,我会假定你已经有了一定的编程基础,因此我会跳过大部分非Python语言的相关内容。本文将高亮显示重要的关键字,以便你可以很容易看到它们。另外需要注意的是,由于本教程篇幅有限,有很多内容我会直接使用代码来说明加以少许注释。
Python的语言特性
Python是一门具有强类型(即变量类型是强制要求的)、动态性、隐式类型(不需要做变量声明)、大小写敏感(var和VAR代表了不同的变量)以及面向对象(一切皆为对象)等特点的编程语言。
获取帮助
你可以很容易的通过Python解释器获取帮助。如果你想知道一个对象(object)是如何工作的,那么你所需要做的就是调用help(
>>>help(5) Helponintobject: (etcetc)>>>dir(5) ['__abs__','__add__',...]>>>abs.__doc__'abs(number)->number Returntheabsolutevalueoftheargument.'
语法
Python中没有强制的语句终止字符,且代码块是通过缩进来指示的。缩进表示一个代码块的开始,逆缩进则表示一个代码块的结束。声明以冒号(:)字符结束,并且开启一个缩进级别。单行注释以井号字符(#)开头,多行注释则以多行字符串的形式出现。赋值(事实上是将对象绑定到名字)通过等号(“=”)实现,双等号(“==”)用于相等判断,”+=”和”-=”用于增加/减少运算(由符号右边的值确定增加/减少的值)。这适用于许多数据类型,包括字符串。你也可以在一行上使用多个变量。例如:
>>>myvar=3>>>myvar+=2>>>myvar5>>>myvar-=1>>>myvar4"""Thisisamultilinecomment. Thefollowinglinesconcatenatethetwostrings.""">>>mystring="Hello">>>mystring+="world.">>>printmystring Helloworld.#Thisswapsthevariablesinoneline(!).#Itdoesn'tviolatestrongtypingbecausevaluesaren't#actuallybeingassigned,butnewobjectsareboundto#theoldnames.>>>myvar,mystring=mystring,myvar
数据类型
Python具有列表(list)、元组(tuple)和字典(dictionaries)三种基本的数据结构,而集合(sets)则包含在集合库中(但从Python2.5版本开始正式成为Python内建类型)。列表的特点跟一维数组类似(当然你也可以创建类似多维数组的“列表的列表”),字典则是具有关联关系的数组(通常也叫做哈希表),而元组则是不可变的一维数组(Python中“数组”可以包含任何类型的元素,这样你就可以使用混合元素,例如整数、字符串或是嵌套包含列表、字典或元组)。数组中第一个元素索引值(下标)为0,使用负数索引值能够从后向前访问数组元素,-1表示最后一个元素。数组元素还能指向函数。来看下面的用法:
>>>sample=[1,["another","list"],("a","tuple")]>>>mylist=["Listitem1",2,3.14]>>>mylist[0]="Listitem1again"#We'rechangingtheitem.>>>mylist[-1]=3.21#Here,werefertothelastitem.>>>mydict={"Key1":"Value1",2:3,"pi":3.14}>>>mydict["pi"]=3.15#Thisishowyouchangedictionaryvalues.>>>mytuple=(1,2,3)>>>myfunction=len>>>printmyfunction(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]#Addingathirdparameter,"step"willhavePythonstepin#Nitemincrements,ratherthan1.#E.g.,thiswillreturnthefirstitem,thengotothethirdand#returnthat(so,items0and2in0-indexing).>>>printmylist[::2] ['Listitem1',3.14]
字符串
Python中的字符串使用单引号(‘)或是双引号(“)来进行标示,并且你还能够在通过某一种标示的字符串中使用另外一种标示符(例如“Hesaid‘hello'.”)。而多行字符串可以通过三个连续的单引号(”')或是双引号(“””)来进行标示。Python可以通过u”Thisisaunicodestring”这样的语法使用Unicode字符串。如果想通过变量来填充字符串,那么可以使用取模运算符(%)和一个元组。使用方式是在目标字符串中从左至右使用%s来指代变量的位置,或者使用字典来代替,示例如下:
>>>print"Name:%s\ Number:%s\ String:%s"%(myclass.name,3,3*"-") Name:Poromenos Number:3String:--- strString="""Thisis amultiline string."""#WARNING:Watchoutforthetrailingsin"%(key)s".>>>print"This%(verb)sa%(noun)s."%{"noun":"test","verb":"is"} Thisisatest.
流程控制
Python中可以使用if、for和while来实现流程控制。Python中并没有select,取而代之使用if来实现。使用for来枚举列表中的元素。如果希望生成一个由数字组成的列表,则可以使用range(
rangelist=range(10)>>>printrangelist [0,1,2,3,4,5,6,7,8,9]fornumberinrangelist:#Checkifnumberisoneof #thenumbersinthetuple. ifnumberin(3,4,7,9):#"Break"terminatesaforwithout #executingthe"else"clause. break else:#"Continue"startsthenextiteration #oftheloop.It'sratheruselesshere, #asit'sthelaststatementoftheloop. continueelse:#The"else"clauseisoptionalandis #executedonlyiftheloopdidn't"break". pass#Donothingifrangelist[1]==2:print"Theseconditem(listsare0-based)is2"elifrangelist[1]==3:print"Theseconditem(listsare0-based)is3"else:print"Dunno"whilerangelist[1]==1:pass
函数
函数通过“def”关键字进行声明。可选参数以集合的方式出现在函数声明中并紧跟着必选参数,可选参数可以在函数声明中被赋予一个默认值。已命名的参数需要赋值。函数可以返回一个元组(使用元组拆包可以有效返回多个值)。Lambda函数是由一个单独的语句组成的特殊函数,参数通过引用进行传递,但对于不可变类型(例如元组,整数,字符串等)则不能够被改变。这是因为只传递了该变量的内存地址,并且只有丢弃了旧的对象后,变量才能绑定一个对象,所以不可变类型是被替换而不是改变(译者注:虽然Python传递的参数形式本质上是引用传递,但是会产生值传递的效果)。例如:
#作用等同于deffuncvar(x):returnx+1funcvar=lambdax:x+1>>>printfuncvar(1)2#an_int和a_string是可选参数,它们有默认值#如果调用passing_example时只指定一个参数,那么an_int缺省为2,a_string缺省为Adefaultstring。如果调用passing_example时指定了前面两个参数,a_string仍缺省为Adefaultstring。#a_list是必备参数,因为它没有指定缺省值。defpassing_example(a_list,an_int=2,a_string="Adefaultstring"): a_list.append("Anewitem") an_int=4 returna_list,an_int,a_string>>>my_list=[1,2,3]>>>my_int=10>>>printpassing_example(my_list,my_int) ([1,2,3,'Anewitem'],4,"Adefaultstring")>>>my_list [1,2,3,'Anewitem']>>>my_int10
类
Python支持有限的多继承形式。私有变量和方法可以通过添加至少两个前导下划线和最多尾随一个下划线的形式进行声明(如“__spam”,这只是惯例,而不是Python的强制要求)。当然,我们也可以给类的实例取任意名称。例如:
classMyClass(object): common=10 def__init__(self): self.myvariable=3 defmyfunction(self,arg1,arg2): returnself.myvariable#Thisistheclassinstantiation>>>classinstance=MyClass()>>>classinstance.myfunction(1,2)3#Thisvariableissharedbyallclasses.>>>classinstance2=MyClass()>>>classinstance.common10>>>classinstance2.common10#Notehowweusetheclassname#insteadoftheinstance.>>>MyClass.common=30>>>classinstance.common30>>>classinstance2.common30#Thiswillnotupdatethevariableontheclass,#insteaditwillbindanewobjecttotheold#variablename.>>>classinstance.common=10>>>classinstance.common10>>>classinstance2.common30>>>MyClass.common=50#Thishasnotchanged,because"common"is#nowaninstancevariable.>>>classinstance.common10>>>classinstance2.common50#ThisclassinheritsfromMyClass.Theexample#classaboveinheritsfrom"object",whichmakes#itwhat'scalleda"new-styleclass".#Multipleinheritanceisdeclaredas:#classOtherClass(MyClass1,MyClass2,MyClassN)classOtherClass(MyClass): #The"self"argumentispassedautomatically #andreferstotheclassinstance,soyoucanset #instancevariablesasabove,butfrominsidetheclass. def__init__(self,arg1): self.myvariable=3 printarg1>>>classinstance=OtherClass("hello") hello>>>classinstance.myfunction(1,2)3#Thisclassdoesn'thavea.testmember,but#wecanaddonetotheinstanceanyway.Note#thatthiswillonlybeamemberofclassinstance.>>>classinstance.test=10>>>classinstance.test10
异常
Python中的异常由try-except[exceptionname]块处理,例如:
defsome_function(): try:#Divisionbyzeroraisesanexception 10/0 exceptZeroDivisionError:print"Oops,invalid." else:#Exceptiondidn'toccur,we'regood. pass finally:#Thisisexecutedafterthecodeblockisrun #andallexceptionshavebeenhandled,even #ifanewexceptionisraisedwhilehandling. print"We'redonewiththat.">>>some_function() Oops,invalid. We'redonewiththat.
导入
外部库可以使用import[libname]关键字来导入。同时,你还可以用from[libname]import[funcname]来导入所需要的函数。例如:
importrandomfromtimeimportclock randomint=random.randint(1,100)>>>printrandomint64
文件I/O
Python针对文件的处理有很多内建的函数库可以调用。例如,这里演示了如何序列化文件(使用pickle库将数据结构转换为字符串):
importpickle mylist=["This","is",4,13327]#OpenthefileC:\\binary.datforwriting.Theletterrbeforethe#filenamestringisusedtopreventbackslashescaping.myfile=open(r"C:\\binary.dat","w") pickle.dump(mylist,myfile) myfile.close() myfile=open(r"C:\\text.txt","w") myfile.write("Thisisasamplestring") myfile.close() myfile=open(r"C:\\text.txt")>>>printmyfile.read()'Thisisasamplestring'myfile.close()#Openthefileforreading.myfile=open(r"C:\\binary.dat") loadedlist=pickle.load(myfile) myfile.close()>>>printloadedlist ['This','is',4,13327]
其它杂项
- 数值判断可以链接使用,例如1
- 可以使用del删除变量或删除数组中的元素。
- 列表推导式(ListComprehension)提供了一个创建和操作列表的有力工具。列表推导式由一个表达式以及紧跟着这个表达式的for语句构成,for语句还可以跟0个或多个if或for语句,来看下面的例子:
>>>lst1=[1,2,3]>>>lst2=[3,4,5]>>>print[x*yforxinlst1foryinlst2] [3,4,5,6,8,10,9,12,15]>>>print[xforxinlst1if4>x>1] [2,3]#Checkifanitemhasaspecificproperty.#"any"returnstrueifanyiteminthelististrue.>>>any([i%3foriin[3,3,4,4,3]])True#Thisisbecause4%3=1,and1istrue,soany()#returnsTrue.#Checkhowmanyitemshavethisproperty.>>>sum(1foriin[3,3,4,4,3]ifi==4)2>>>dellst1[0]>>>printlst1 [2,3]>>>dellst1
全局变量在函数之外声明,并且可以不需要任何特殊的声明即能读取,但如果你想要修改全局变量的值,就必须在函数开始之处用global关键字进行声明,否则Python会将此变量按照新的局部变量处理(请注意,如果不注意很容易被坑)。例如:
number=5defmyfunc(): #Thiswillprint5. printnumberdefanotherfunc(): #Thisraisesanexceptionbecausethevariablehasnot #beenboundbeforeprinting.Pythonknowsthatitan #objectwillbeboundtoitlaterandcreatesanew,local #objectinsteadofaccessingtheglobalone. printnumber number=3defyetanotherfunc(): globalnumber#Thiswillcorrectlychangetheglobal. number=3
推荐书单:
你眼中的Python大牛应该都有这份书单
Python书单不将就
不可错过的十本Python好书
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。