>  기사  >  백엔드 개발  >  Python의 조건, 루프 등에 대한 소개

Python의 조건, 루프 등에 대한 소개

高洛峰
高洛峰원래의
2017-03-08 11:06:351470검색

사전에서 키-값 쌍 가져오기

>>> 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
rrree

번호가 매겨진 반복

>>> 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;

True/break

>>> for n in range(99,0,-1):
    m=sqrt(n)
    if m==int(m):
        print n
        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:

List comprehension-lightweight loop

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

    
h

pass

>>> [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;]

del x와 y의 else 문은 동시에 목록을 가리키지만 x를 삭제하면 y에는 영향을 미치지 않습니다. 목록 자체(값)는 삭제되지 않고 이름만 삭제됩니다.

>>> 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;

exec

>>> 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;]

참고: 네임스페이스를 범위라고 합니다. 보이지 않는 사전과 마찬가지로 변수를 보관하는 장소라고 생각하세요. x=1과 같은 할당문을 실행하면 키 x와 값 1이 현재 네임스페이스에 배치됩니다. 이 네임스페이스는 일반적으로 전역 네임스페이스입니다.

>>> 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;]

평가는

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

Python의 조건, 루프 등에 대한 소개


위 내용은 Python의 조건, 루프 등에 대한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.