PHP前端开发

python中条件、循环等介绍说明

百变鹏仔 3小时前 #Python
文章标签 条件

获取字典中任意的键-值对

&gt;&gt;&gt; x={'a':1,'b':2}&gt;&gt;&gt; key,value=x.popitem()&gt;&gt;&gt; key,value('a', 1)&gt;&gt;&gt; del x[key]Traceback (most recent call last):  File "<pyshell>", line 1, in <module>    del x[key]KeyError: 'a'&gt;&gt;&gt; x{'b': 2}&gt;&gt;&gt; x[key]=value&gt;&gt;&gt; x{'a': 1, 'b': 2}&gt;&gt;&gt; del x[key]</module></pyshell>

 增量赋值

&gt;&gt;&gt; x=2&gt;&gt;&gt; x+=1&gt;&gt;&gt; x*=2&gt;&gt;&gt; x&gt;&gt;&gt; fnord='foo'&gt;&gt;&gt; fnord+='bar'&gt;&gt;&gt; fnord*=2&gt;&gt;&gt; fnord'foobarfoobar'

条件执行if语句

&gt;&gt;&gt; name=raw_input('?')?Yq Z&gt;&gt;&gt; if name.endswith('Z'):     print 'Hello,Mr.Z'Hello,Mr.Z

else子句

&gt;&gt;&gt; name=raw_input('what is your name?')what is your name?Yq Z&gt;&gt;&gt; if name.endswith('Z'):    print 'Hello,Mr.Z'else:    print 'Hello,stranger'    Hello,Mr.Z

elif子句 

立即学习“Python免费学习笔记(深入)”;

&gt;&gt;&gt; num=input('Enter a number: ')Enter a number: 5&gt;&gt;&gt; if num&gt;0:    print 'The number is position'elif num<p>条件嵌套语句</p><pre class="brush:python;toolbar:false">&gt;&gt;&gt; name=raw_input('What is your name?')What is your name?Yq Z&gt;&gt;&gt; if name.endswith('Yq'):    if name.startswith('Z'):        print 'Hello,Yq Z'    elif name.startswith('K'):        print 'Hello,Zyq'    else:        print 'Hello,Yq'else:    print 'Hello,stranger'    Hello,stranger
&gt;&gt;&gt; number=input('Enter a number between 1 and 10:')Enter a number between 1 and 10:6&gt;&gt;&gt; if number=1:    print 'Great!'else:    print 'Wrong!'    Great!
&gt;&gt;&gt; age=10&gt;&gt;&gt; assert 0<age>&gt;&gt; age=-1&gt;&gt;&gt; assert 0<age traceback>", line 1, in <module>    assert 0<age assertionerror><p>while循环</p><pre class="brush:python;toolbar:false">&gt;&gt;&gt; x=1&gt;&gt;&gt; while x<pre class="brush:python;toolbar:false">&gt;&gt;&gt; while not name:    name=raw_input('Please enter your name:')    print 'Hello,%s !' % name    Please enter your name:zyqHello,zyq !

for循环

&gt;&gt;&gt; words=['this','is','an','ex','parrot']&gt;&gt;&gt; for word in words:    print word    thisisanexparrot&gt;&gt;&gt; range(0,10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]&gt;&gt;&gt; for i in range(1,8):    print i246

字典循环(迭代)

&gt;&gt;&gt; d={'x':1,'y':2,'z':3}&gt;&gt;&gt; for key in d:    print key,'corresponds to',d[key]    y corresponds to 2x corresponds to 1z corresponds to 3

 并行迭代

&gt;&gt;&gt; names=['Anne','Beth','George','Damon']  &gt;&gt;&gt; ages=[12,19,18,20]&gt;&gt;&gt; for i in range(len(names)):    print names[i],'is',ages[i],'years old'    Anne is 12 years oldBeth is 19 years oldGeorge is 18 years oldDamon is 20 years old
&gt;&gt;&gt; zip(names,ages)[('Anne', 12), ('Beth', 19), ('George', 18), ('Damon', 20)]&gt;&gt;&gt; for name,age in zip(names,ages):    print name,'is',age,'years old'    Anne is 12 years oldBeth is 19 years oldGeorge is 18 years oldDamon is 20 years old&gt;&gt;&gt; zip(range(5),xrange(100))[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

编号迭代

&gt;&gt;&gt; d[1, 2, 4, 4]&gt;&gt;&gt; for x in d:    if x==4:        d[d.index(x)]=6        &gt;&gt;&gt; d[1, 2, 6, 6]&gt;&gt;&gt; S=['skj','kiu','olm','piy']&gt;&gt;&gt; index=0&gt;&gt;&gt; for s1 in S:    if 'k' in s1:        S[index]='HH'    index+=1    &gt;&gt;&gt; S['HH', 'HH', 'olm', 'piy']&gt;&gt;&gt; for index,s2 in enumerate(S): #enumerate函数提供索引-值对    if 'H' in s2:        S[index]='DF'        &gt;&gt;&gt; S['DF', 'DF', 'olm', 'piy']

翻转、排序迭代

&gt;&gt;&gt; sorted([4,3,6,8,3])[3, 3, 4, 6, 8]&gt;&gt;&gt; sorted('Hello,world!')['!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']&gt;&gt;&gt; list(reversed('Hello,world!'))['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H']&gt;&gt;&gt; ''.join(reversed('Hello,world!'))'!dlrow,olleH'

 break跳出循环

&gt;&gt;&gt; for n in range(99,0,-1):    m=sqrt(n)    if m==int(m):        print n        break

 while True/break

&gt;&gt;&gt; while True:    word=raw_input('Please enter a word:')    if not word:break    print 'The word was '+word    Please enter a word:fThe word was fPlease enter a word:

循环中的else语句

&gt;&gt;&gt; for n in range(99,81,-1):    m=sqrt(n)    if m==int(m):        print m        breakelse:    print 'h'    h

 列表推导式-轻量级循环

&gt;&gt;&gt; [x*x for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]&gt;&gt;&gt; [x*x for x in range(10) if x%3==0][0, 9, 36, 81]&gt;&gt;&gt; [(x,y) for x in range(3) for y in range (3)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]&gt;&gt;&gt; result=[]&gt;&gt;&gt; for x in range(3):    for y in range(3):        result.append((x,y))&gt;&gt;&gt; result [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]&gt;&gt;&gt; girls=['Alice','Bernice','Clarice']&gt;&gt;&gt; boys=['Chris','Arnold','Bob']&gt;&gt;&gt; [b+'+'+g for b in boys for g in girls if b[0]==g[0]]['Chris+Clarice', 'Arnold+Alice', 'Bob+Bernice']

 pass

&gt;&gt;&gt; if name=='Nsds':    print 'Welcome!'elif name=='UK':    #还没完    passelif name=='Bill':    print 'Access Denied'else:    print 'Nobody!'

 del x和y同时指向一个列表,但是删除x并不会影响y。删除的只是名称,不是列表本身(值)

&gt;&gt;&gt; x=['Hello','world']&gt;&gt;&gt; y=x&gt;&gt;&gt; y[1]='Python'&gt;&gt;&gt; x['Hello', 'Python']&gt;&gt;&gt; del x&gt;&gt;&gt; y['Hello', 'Python']

exec

&gt;&gt;&gt; exec "print 'Hello,world!'"Hello,world!&gt;&gt;&gt; from math import sqrt&gt;&gt;&gt; exec "sqrt=1"&gt;&gt;&gt; sqrt(4)Traceback (most recent call last):  File "<pyshell>", line 1, in <module>    sqrt(4)TypeError: 'int' object is not callable#增加一个字典,起到命名空间的作用&gt;&gt;&gt; from math import sqrt&gt;&gt;&gt; scope={}&gt;&gt;&gt; exec 'sqrt=1' in scope&gt;&gt;&gt; sqrt(4)2.0&gt;&gt;&gt; scope['sqrt']</module></pyshell>

注意:命名空间,称作作用域。可以把它想象成保存变量的地方,类似于不可见的字典。执行 x=1这类赋值语句时,就将键x和值1放在当前的命名空间内,这个命名空间一般来说都是全局命名空间。

&gt;&gt;&gt; len(scope)2&gt;&gt;&gt; scope.keys()['__builtins__', 'sqrt']

eval 求值

&gt;&gt;&gt; scope={}&gt;&gt;&gt; scope['x']=2&gt;&gt;&gt; scope['y']=3&gt;&gt;&gt; eval('x*y',scope)&gt;&gt;&gt; scope={}&gt;&gt;&gt; exec 'x=2' in scope&gt;&gt;&gt; eval('x*x',scope)