Rumah  >  Artikel  >  pembangunan bahagian belakang  >  python中条件、循环等介绍说明

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

高洛峰
高洛峰asal
2017-03-08 11:06:351439semak imbas

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

>>> x={'a':1,'b':2}
>>> key,value=x.popitem()
>>> key,value
('a', 1)
>>> del x[key]

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

 增量赋值

>>> x=2
>>> x+=1
>>> x*=2
>>> x
>>> fnord=&#39;foo&#39;
>>> fnord+=&#39;bar&#39;
>>> fnord*=2
>>> fnord
&#39;foobarfoobar&#39;

条件执行if语句

>>> name=raw_input(&#39;?&#39;)
?Yq Z
>>> if name.endswith(&#39;Z&#39;):  \
   print &#39;Hello,Mr.Z&#39;

Hello,Mr.Z

else子句

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

    
Hello,Mr.Z

elif子句 

>>> num=input(&#39;Enter a number: &#39;)
Enter a number: 5
>>> if num>0:
    print &#39;The number is position&#39;
elif num<0:
    print &#39;The number is negative&#39;
else:
    print &#39;The number is zero&#39;

    
The number is position

条件嵌套语句

>>> name=raw_input(&#39;What is your name?&#39;)
What is your name?Yq Z
>>> if name.endswith(&#39;Yq&#39;):
    if name.startswith(&#39;Z&#39;):
        print &#39;Hello,Yq Z&#39;
    elif name.startswith(&#39;K&#39;):
        print &#39;Hello,Zyq&#39;
    else:
        print &#39;Hello,Yq&#39;
else:
    print &#39;Hello,stranger&#39;

    
Hello,stranger
>>> number=input(&#39;Enter a number between 1 and 10:&#39;)
Enter a number between 1 and 10:6
>>> if number<=10 and number>=1:
    print &#39;Great!&#39;
else:
    print &#39;Wrong!&#39;

    
Great!
>>> age=10
>>> assert 0<age<100
>>> age=-1
>>> assert 0<age<100

Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    assert 0<age<100
AssertionError

while循环

>>> x=1
>>> while x<=100:
    print x
    x+=1
>>> while not name:
    name=raw_input(&#39;Please enter your name:&#39;)
    print &#39;Hello,%s !&#39; % name

    
Please enter your name:zyq
Hello,zyq !

for循环

>>> words=[&#39;this&#39;,&#39;is&#39;,&#39;an&#39;,&#39;ex&#39;,&#39;parrot&#39;]
>>> for word in words:
    print word

    
this
is
an
ex
parrot
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(1,8):
    print i
2
4
6

字典循环(迭代)

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

    
y corresponds to 2
x corresponds to 1
z corresponds to 3

 并行迭代

>>> names=[&#39;Anne&#39;,&#39;Beth&#39;,&#39;George&#39;,&#39;Damon&#39;]
  >>> ages=[12,19,18,20]
>>> for i in range(len(names)):
    print names[i],&#39;is&#39;,ages[i],&#39;years old&#39;

    
Anne is 12 years old
Beth is 19 years old
George is 18 years old
Damon is 20 years old
>>> zip(names,ages)
[(&#39;Anne&#39;, 12), (&#39;Beth&#39;, 19), (&#39;George&#39;, 18), (&#39;Damon&#39;, 20)]
>>> for name,age in zip(names,ages):
    print name,&#39;is&#39;,age,&#39;years old&#39;

    
Anne is 12 years old
Beth is 19 years old
George is 18 years old
Damon is 20 years old
>>> zip(range(5),xrange(100))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

编号迭代

>>> d
[1, 2, 4, 4]
>>> for x in d:
    if x==4:
        d[d.index(x)]=6

        
>>> d
[1, 2, 6, 6]
>>> S=[&#39;skj&#39;,&#39;kiu&#39;,&#39;olm&#39;,&#39;piy&#39;]
>>> index=0>>> for s1 in S:
    if &#39;k&#39; in s1:
        S[index]=&#39;HH&#39;
    index+=1

    
>>> S
[&#39;HH&#39;, &#39;HH&#39;, &#39;olm&#39;, &#39;piy&#39;]>>> for index,s2 in enumerate(S): #enumerate函数提供索引-值对
    if &#39;H&#39; in s2:
        S[index]=&#39;DF&#39;

        
>>> S
[&#39;DF&#39;, &#39;DF&#39;, &#39;olm&#39;, &#39;piy&#39;]

翻转、排序迭代

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

 break跳出循环

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

 while True/break

>>> while True:
    word=raw_input(&#39;Please enter a word:&#39;)
    if not word:break
    print &#39;The word was &#39;+word

    
Please enter a word:f
The word was f
Please enter a word:

循环中的else语句

>>> for n in range(99,81,-1):
    m=sqrt(n)
    if m==int(m):
        print m
        break
else:
    print &#39;h&#39;

    
h

 列表推导式-轻量级循环

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]
>>> [(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)]
>>> result=[]
>>> for x in range(3):
    for y in range(3):
        result.append((x,y))
>>> result
 [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> girls=[&#39;Alice&#39;,&#39;Bernice&#39;,&#39;Clarice&#39;]
>>> boys=[&#39;Chris&#39;,&#39;Arnold&#39;,&#39;Bob&#39;]
>>> [b+&#39;+&#39;+g for b in boys for g in girls if b[0]==g[0]]
[&#39;Chris+Clarice&#39;, &#39;Arnold+Alice&#39;, &#39;Bob+Bernice&#39;]

 pass

>>> if name==&#39;Nsds&#39;:
    print &#39;Welcome!&#39;
elif name==&#39;UK&#39;:
    #还没完
    pass
elif name==&#39;Bill&#39;:
    print &#39;Access Denied&#39;
else:
    print &#39;Nobody!&#39;

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

>>> x=[&#39;Hello&#39;,&#39;world&#39;]
>>> y=x
>>> y[1]=&#39;Python&#39;
>>> x
[&#39;Hello&#39;, &#39;Python&#39;]
>>> del x
>>> y
[&#39;Hello&#39;, &#39;Python&#39;]

exec

>>> exec "print &#39;Hello,world!&#39;"
Hello,world!
>>> from math import sqrt
>>> exec "sqrt=1"
>>> sqrt(4)

Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    sqrt(4)
TypeError: &#39;int&#39; object is not callable

#增加一个字典,起到命名空间的作用
>>> from math import sqrt
>>> scope={}
>>> exec &#39;sqrt=1&#39; in scope
>>> sqrt(4)
2.0
>>> scope[&#39;sqrt&#39;]

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

>>> len(scope)2
>>> scope.keys()
[&#39;__builtins__&#39;, &#39;sqrt&#39;]

eval 求值

>>> scope={}
>>> scope[&#39;x&#39;]=2
>>> scope[&#39;y&#39;]=3
>>> eval(&#39;x*y&#39;,scope)
>>> scope={}
>>> exec &#39;x=2&#39; in scope
>>> eval(&#39;x*x&#39;,scope)

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


Atas ialah kandungan terperinci python中条件、循环等介绍说明. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:python dict字典详细说明Artikel seterusnya:Python正则表达式总结