分分钟入门python语言
Python是90年代初由GuidoVanRossum创立的。它是当前最流行的程序语言之一。它那纯净的语法令我一见倾心,它简直就是可以运行的伪码。
请注意:本文以Python2.7为基准,但也应该适用于所有2.X版本。还要继续学习最新的Python3哦!
#Singlelinecommentsstartwithahash.
#单行注释由一个井号开头。
"""Multilinestringscanbewritten
usingthree"'s,andareoftenused
ascomments
三个双引号(或单引号)之间可以写多行字符串,
通常用来写注释。
"""
####################################################
##1.PrimitiveDatatypesandOperators
##1.基本数据类型和操作符
####################################################
#Youhavenumbers
#数字就是数字
3#=>3
#Mathiswhatyouwouldexpect
#四则运算也是你所期望的那样
1+1#=>2
8-1#=>7
10*2#=>20
35/5#=>7
#Divisionisabittricky.Itisintegerdivisionandfloorstheresults
#automatically.
#除法有一点棘手。
#对于整数除法来说,计算结果会自动取整。
5/2#=>2
#Tofixdivisionweneedtolearnaboutfloats.
#为了修正除法的问题,我们需要先学习浮点数。
2.0#Thisisafloat
2.0#这是一个浮点数
11.0/4.0#=>2.75ahhh...muchbetter
11.0/4.0#=>2.75啊……这样就好多了
#Enforceprecedencewithparentheses
#使用小括号来强制计算的优先顺序
(1+3)*2#=>8
#Booleanvaluesareprimitives
#布尔值也是基本数据类型
True
False
#negatewithnot
#使用not来取反
notTrue#=>False
notFalse#=>True
#Equalityis==
#等式判断用==
1==1#=>True
2==1#=>False
#Inequalityis!=
#不等式判断是用!=
1!=1#=>False
2!=1#=>True
#Morecomparisons
#还有更多的比较运算
1<10#=>True
1>10#=>False
2<=2#=>True
2>=2#=>True
#Comparisonscanbechained!
#居然可以把比较运算串连起来!
1<2<3#=>True
2<3<2#=>False
#Stringsarecreatedwith"or'
#使用"或'来创建字符串
"Thisisastring."
'Thisisalsoastring.'
#Stringscanbeaddedtoo!
#字符串也可以相加!
"Hello"+"world!"#=>"Helloworld!"
#Astringcanbetreatedlikealistofcharacters
#一个字符串可以视为一个字符的列表
#(译注:后面会讲到“列表”。)
"Thisisastring"[0]#=>'T'
#%canbeusedtoformatstrings,likethis:
#%可以用来格式化字符串,就像这样:
"%scanbe%s"%("strings","interpolated")
#Anewerwaytoformatstringsistheformatmethod.
#Thismethodisthepreferredway
#后来又有一种格式化字符串的新方法:format方法。
#我们推荐使用这个方法。
"{0}canbe{1}".format("strings","formatted")
#Youcanusekeywordsifyoudon'twanttocount.
#如果你不喜欢数数的话,可以使用关键字(变量)。
"{name}wantstoeat{food}".format(name="Bob",food="lasagna")
#Noneisanobject
#None是一个对象
None#=>None
#Don'tusetheequality`==`symboltocompareobjectstoNone
#Use`is`instead
#不要使用相等符号`==`来把对象和None进行比较,
#而要用`is`。
"etc"isNone#=>False
NoneisNone#=>True
#The'is'operatortestsforobjectidentity.Thisisn't
#veryusefulwhendealingwithprimitivevalues,butis
#veryusefulwhendealingwithobjects.
#这个`is`操作符用于比较两个对象的标识。
#(译注:对象一旦建立,其标识就不会改变,可以认为它就是对象的内存地址。)
#在处理基本数据类型时基本用不上,
#但它在处理对象时很有用。
#None,0,andemptystrings/listsallevaluatetoFalse.
#AllothervaluesareTrue
#None、0以及空字符串和空列表都等于False,
#除此以外的所有值都等于True。
0==False#=>True
""==False#=>True
####################################################
##2.VariablesandCollections
##2.变量和集合
####################################################
#Printingisprettyeasy
#打印输出很简单
print"I'mPython.Nicetomeetyou!"
#Noneedtodeclarevariablesbeforeassigningtothem.
#在赋值给变量之前不需要声明
some_var=5#Conventionistouselower_case_with_underscores
#变量名的约定是使用下划线分隔的小写单词
some_var#=>5
#Accessingapreviouslyunassignedvariableisanexception.
#SeeControlFlowtolearnmoreaboutexceptionhandling.
#访问一个未赋值的变量会产生一个异常。
#进一步了解异常处理,可参见下一节《控制流》。
some_other_var#Raisesanameerror
#会抛出一个名称错误
#ifcanbeusedasanexpression
#if可以作为表达式来使用
"yahoo!"if3>2else2#=>"yahoo!"
#Listsstoresequences
#列表用于存储序列
li=[]
#Youcanstartwithaprefilledlist
#我们先尝试一个预先填充好的列表
other_li=[4,5,6]
#Addstufftotheendofalistwithappend
#使用append方法把元素添加到列表的尾部
li.append(1)#liisnow[1]
#li现在是[1]
li.append(2)#liisnow[1,2]
#li现在是[1,2]
li.append(4)#liisnow[1,2,4]
#li现在是[1,2,4]
li.append(3)#liisnow[1,2,4,3]
#li现在是[1,2,4,3]
#Removefromtheendwithpop
#使用pop来移除最后一个元素
li.pop()#=>3andliisnow[1,2,4]
#=>3,然后li现在是[1,2,4]
#Let'sputitback
#我们再把它放回去
li.append(3)#liisnow[1,2,4,3]again.
#li现在又是[1,2,4,3]了
#Accessalistlikeyouwouldanyarray
#像访问其它语言的数组那样访问列表
li[0]#=>1
#Lookatthelastelement
#查询最后一个元素
li[-1]#=>3
#LookingoutofboundsisanIndexError
#越界查询会产生一个索引错误
li[4]#RaisesanIndexError
#抛出一个索引错误
#Youcanlookatrangeswithslicesyntax.
#(It'saclosed/openrangeforyoumathytypes.)
#你可以使用切片语法来查询列表的一个范围。
#(这个范围相当于数学中的左闭右开区间。)
li[1:3]#=>[2,4]
#Omitthebeginning
#省略开头
li[2:]#=>[4,3]
#Omittheend
#省略结尾
li[:3]#=>[1,2,4]
#Removearbitraryelementsfromalistwithdel
#使用del来删除列表中的任意元素
delli[2]#liisnow[1,2,3]
#li现在是[1,2,3]
#Youcanaddlists
#可以把列表相加
li+other_li#=>[1,2,3,4,5,6]-Note:liandother_liisleftalone
#=>[1,2,3,4,5,6]-请留意li和other_li并不会被修改
#Concatenatelistswithextend
#使用extend来合并列表
li.extend(other_li)#Nowliis[1,2,3,4,5,6]
#现在li是[1,2,3,4,5,6]
#Checkforexistenceinalistwithin
#用in来检查是否存在于某个列表中
1inli#=>True
#Examinethelengthwithlen
#用len来检测列表的长度
len(li)#=>6
#Tuplesarelikelistsbutareimmutable.
#元组很像列表,但它是“不可变”的。
tup=(1,2,3)
tup[0]#=>1
tup[0]=3#RaisesaTypeError
#抛出一个类型错误
#Youcandoallthoselistthingiesontuplestoo
#操作列表的方式通常也能用在元组身上
len(tup)#=>3
tup+(4,5,6)#=>(1,2,3,4,5,6)
tup[:2]#=>(1,2)
2intup#=>True
#Youcanunpacktuples(orlists)intovariables
#你可以把元组(或列表)中的元素解包赋值给多个变量
a,b,c=(1,2,3)#aisnow1,bisnow2andcisnow3
#现在a是1,b是2,c是3
#Tuplesarecreatedbydefaultifyouleaveouttheparentheses
#如果你省去了小括号,那么元组会被自动创建
d,e,f=4,5,6
#Nowlookhoweasyitistoswaptwovalues
#再来看看交换两个值是多么简单。
e,d=d,e#disnow5andeisnow4
#现在d是5而e是4
#Dictionariesstoremappings
#字典用于存储映射关系
empty_dict={}
#Hereisaprefilleddictionary
#这是一个预先填充的字典
filled_dict={"one":1,"two":2,"three":3}
#Lookupvalueswith[]
#使用[]来查询键值
filled_dict["one"]#=>1
#Getallkeysasalist
#将字典的所有键名获取为一个列表
filled_dict.keys()#=>["three","two","one"]
#Note-Dictionarykeyorderingisnotguaranteed.
#Yourresultsmightnotmatchthisexactly.
#请注意:无法保证字典键名的顺序如何排列。
#你得到的结果可能跟上面的示例不一致。
#Getallvaluesasalist
#将字典的所有键值获取为一个列表
filled_dict.values()#=>[3,2,1]
#Note-Sameasaboveregardingkeyordering.
#请注意:顺序的问题和上面一样。
#Checkforexistenceofkeysinadictionarywithin
#使用in来检查一个字典是否包含某个键名
"one"infilled_dict#=>True
1infilled_dict#=>False
#Lookingupanon-existingkeyisaKeyError
#查询一个不存在的键名会产生一个键名错误
filled_dict["four"]#KeyError
#键名错误
#UsegetmethodtoavoidtheKeyError
#所以要使用get方法来避免键名错误
filled_dict.get("one")#=>1
filled_dict.get("four")#=>None
#Thegetmethodsupportsadefaultargumentwhenthevalueismissing
#get方法支持传入一个默认值参数,将在取不到值时返回。
filled_dict.get("one",4)#=>1
filled_dict.get("four",4)#=>4
#Setdefaultmethodisasafewaytoaddnewkey-valuepairintodictionary
#Setdefault方法可以安全地把新的名值对添加到字典里
filled_dict.setdefault("five",5)#filled_dict["five"]issetto5
#filled_dict["five"]被设置为5
filled_dict.setdefault("five",6)#filled_dict["five"]isstill5
#filled_dict["five"]仍然为5
#Setsstore...wellsets
#set用于保存集合
empty_set=set()
#Initializeasetwithabunchofvalues
#使用一堆值来初始化一个集合
some_set=set([1,2,2,3,4])#some_setisnowset([1,2,3,4])
#some_set现在是set([1,2,3,4])
#SincePython2.7,{}canbeusedtodeclareaset
#从Python2.7开始,{}可以用来声明一个集合
filled_set={1,2,2,3,4}#=>{1,2,3,4}
#(译注:集合是种无序不重复的元素集,因此重复的2被滤除了。)
#(译注:{}不会创建一个空集合,只会创建一个空字典。)
#Addmoreitemstoaset
#把更多的元素添加进一个集合
filled_set.add(5)#filled_setisnow{1,2,3,4,5}
#filled_set现在是{1,2,3,4,5}
#Dosetintersectionwith&
#使用&来获取交集
other_set={3,4,5,6}
filled_set&other_set#=>{3,4,5}
#Dosetunionwith|
#使用|来获取并集
filled_set|other_set#=>{1,2,3,4,5,6}
#Dosetdifferencewith-
#使用-来获取补集
{1,2,3,4}-{2,3,5}#=>{1,4}
#Checkforexistenceinasetwithin
#使用in来检查是否存在于某个集合中
2infilled_set#=>True
10infilled_set#=>False
####################################################
##3.ControlFlow
##3.控制流
####################################################
#Let'sjustmakeavariable
#我们先创建一个变量
some_var=5
#Hereisanifstatement.Indentationissignificantinpython!
#prints"some_varissmallerthan10"
#这里有一个条件语句。缩进在Python中可是很重要的哦!
#程序会打印出"some_varissmallerthan10"
#(译注:意为“some_var比10小”。)
ifsome_var>10:
print"some_varistotallybiggerthan10."
#(译注:意为“some_var完全比10大”。)
elifsome_var<10:#Thiselifclauseisoptional.
#这里的elif子句是可选的
print"some_varissmallerthan10."
#(译注:意为“some_var比10小”。)
else:#Thisisoptionaltoo.
#这一句也是可选的
print"some_varisindeed10."
#(译注:意为“some_var就是10”。)
"""
Forloopsiterateoverlists
for循环可以遍历列表
prints:
如果要打印出:
dogisamammal
catisamammal
mouseisamammal
"""
foranimalin["dog","cat","mouse"]:
#Youcanuse%tointerpolateformattedstrings
#别忘了你可以使用%来格式化字符串
print"%sisamammal"%animal
#(译注:意为“%s是哺乳动物”。)
"""
`range(number)`returnsalistofnumbers
fromzerotothegivennumber
`range(数字)`会返回一个数字列表,
这个列表将包含从零到给定的数字。
prints:
如果要打印出:
0
1
2
3
"""
foriinrange(4):
printi
"""
Whileloopsgountilaconditionisnolongermet.
while循环会一直继续,直到条件不再满足。
prints:
如果要打印出:
0
1
2
3
"""
x=0
whilex<4:
printx
x+=1#Shorthandforx=x+1
#这是x=x+1的简写方式
#Handleexceptionswithatry/exceptblock
#使用try/except代码块来处理异常
#WorksonPython2.6andup:
#适用于Python2.6及以上版本:
try:
#Useraisetoraiseanerror
#使用raise来抛出一个错误
raiseIndexError("Thisisanindexerror")
#抛出一个索引错误:“这是一个索引错误”。
exceptIndexErrorase:
pass#Passisjustano-op.Usuallyyouwoulddorecoveryhere.
#pass只是一个空操作。通常你应该在这里做一些恢复工作。
####################################################
##4.Functions
##4.函数
####################################################
#Usedeftocreatenewfunctions
#使用def来创建新函数
defadd(x,y):
print"xis%sandyis%s"%(x,y)
#(译注:意为“x是%s而且y是%s”。)
returnx+y#Returnvalueswithareturnstatement
#使用return语句来返回值
#Callingfunctionswithparameters
#调用函数并传入参数
add(5,6)#=>printsout"xis5andyis6"andreturns11
#(译注:意为“x是5而且y是6”,并返回11)
#Anotherwaytocallfunctionsiswithkeywordarguments
#调用函数的另一种方式是传入关键字参数
add(y=6,x=5)#Keywordargumentscanarriveinanyorder.
#关键字参数可以以任意顺序传入
#Youcandefinefunctionsthattakeavariablenumberof
#positionalarguments
#你可以定义一个函数,并让它接受可变数量的定位参数。
defvarargs(*args):
returnargs
varargs(1,2,3)#=>(1,2,3)
#Youcandefinefunctionsthattakeavariablenumberof
#keywordarguments,aswell
#你也可以定义一个函数,并让它接受可变数量的关键字参数。
defkeyword_args(**kwargs):
returnkwargs
#Let'scallittoseewhathappens
#我们试着调用它,看看会发生什么:
keyword_args(big="foot",loch="ness")#=>{"big":"foot","loch":"ness"}
#Youcandobothatonce,ifyoulike
#你还可以同时使用这两类参数,只要你愿意:
defall_the_args(*args,**kwargs):
printargs
printkwargs
"""
all_the_args(1,2,a=3,b=4)prints:
(1,2)
{"a":3,"b":4}
"""
#Whencallingfunctions,youcandotheoppositeofvarargs/kwargs!
#Use*toexpandtuplesanduse**toexpandkwargs.
#在调用函数时,定位参数和关键字参数还可以反过来用。
#使用*来展开元组,使用**来展开关键字参数。
args=(1,2,3,4)
kwargs={"a":3,"b":4}
all_the_args(*args)#equivalenttofoo(1,2,3,4)
#相当于all_the_args(1,2,3,4)
all_the_args(**kwargs)#equivalenttofoo(a=3,b=4)
#相当于all_the_args(a=3,b=4)
all_the_args(*args,**kwargs)#equivalenttofoo(1,2,3,4,a=3,b=4)
#相当于all_the_args(1,2,3,4,a=3,b=4)
#Pythonhasfirstclassfunctions
#函数在Python中是一等公民
defcreate_adder(x):
defadder(y):
returnx+y
returnadder
add_10=create_adder(10)
add_10(3)#=>13
#Therearealsoanonymousfunctions
#还有匿名函数
(lambdax:x>2)(3)#=>True
#Therearebuilt-inhigherorderfunctions
#还有一些内建的高阶函数
map(add_10,[1,2,3])#=>[11,12,13]
filter(lambdax:x>5,[3,4,5,6,7])#=>[6,7]
#Wecanuselistcomprehensionsfornicemapsandfilters
#我们可以使用列表推导式来模拟map和filter
[add_10(i)foriin[1,2,3]]#=>[11,12,13]
[xforxin[3,4,5,6,7]ifx>5]#=>[6,7]
####################################################
##5.Classes
##5.类
####################################################
#Wesubclassfromobjecttogetaclass.
#我们可以从对象中继承,来得到一个类。
classHuman(object):
#Aclassattribute.Itissharedbyallinstancesofthisclass
#下面是一个类属性。它将被这个类的所有实例共享。
species="H.sapiens"
#Basicinitializer
#基本的初始化函数(构造函数)
def__init__(self,name):
#Assigntheargumenttotheinstance'snameattribute
#把参数赋值为实例的name属性
self.name=name
#Aninstancemethod.Allmethodstakeselfasthefirstargument
#下面是一个实例方法。所有方法都以self作为第一个参数。
defsay(self,msg):
return"%s:%s"%(self.name,msg)
#Aclassmethodissharedamongallinstances
#Theyarecalledwiththecallingclassasthefirstargument
#类方法会被所有实例共享。
#类方法在调用时,会将类本身作为第一个函数传入。
@classmethod
defget_species(cls):
returncls.species
#Astaticmethodiscalledwithoutaclassorinstancereference
#静态方法在调用时,不会传入类或实例的引用。
@staticmethod
defgrunt():
return"*grunt*"
#Instantiateaclass
#实例化一个类
i=Human(name="Ian")
printi.say("hi")#printsout"Ian:hi"
#打印出"Ian:hi"
j=Human("Joel")
printj.say("hello")#printsout"Joel:hello"
#打印出"Joel:hello"
#Callourclassmethod
#调用我们的类方法
i.get_species()#=>"H.sapiens"
#Changethesharedattribute
#修改共享属性
Human.species="H.neanderthalensis"
i.get_species()#=>"H.neanderthalensis"
j.get_species()#=>"H.neanderthalensis"
#Callthestaticmethod
#调用静态方法
Human.grunt()#=>"*grunt*"
####################################################
##6.Modules
##6.模块
####################################################
#Youcanimportmodules
#你可以导入模块
importmath
printmath.sqrt(16)#=>4
#Youcangetspecificfunctionsfromamodule
#也可以从一个模块中获取指定的函数
frommathimportceil,floor
printceil(3.7)#=>4.0
printfloor(3.7)#=>3.0
#Youcanimportallfunctionsfromamodule.
#Warning:thisisnotrecommended
#你可以从一个模块中导入所有函数
#警告:不建议使用这种方式
frommathimport*
#Youcanshortenmodulenames
#你可以缩短模块的名称
importmathasm
math.sqrt(16)==m.sqrt(16)#=>True
#Pythonmodulesarejustordinarypythonfiles.You
#canwriteyourown,andimportthem.Thenameofthe
#moduleisthesameasthenameofthefile.
#Python模块就是普通的Python文件。
#你可以编写你自己的模块,然后导入它们。
#模块的名称与文件名相同。
#Youcanfindoutwhichfunctionsandattributes
#definesamodule.
#你可以查出一个模块里有哪些函数和属性
importmath
dir(math)
SourceFile:adambard/learnxinyminutes-docs-GitHub
Translatedby:cssmagic
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。