Introduction to conditions, loops, etc. in python

高洛峰
Release: 2017-03-08 11:06:35
Original
1480 people have browsed it

Get any key-value pair in the dictionary

>>> 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]
Copy after login

Incremental assignment

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

Conditional execution if statement

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

Hello,Mr.Z
Copy after login

else clause

>>> 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
Copy after login

elif clause

>>> 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
Copy after login

Conditional nested statement

>>> 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
Copy after login
>>> 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!
Copy after login
>>> 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
Copy after login

while loop

>>> x=1
>>> while x<=100:
    print x
    x+=1
Copy after login
>>> 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 !
Copy after login

for loop

>>> 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
Copy after login

Dictionary loop (iteration)

>>> 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
Copy after login

Parallel iteration

>>> 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
Copy after login
>>> 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)]
Copy after login

Numbered iteration

>>> 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;]
Copy after login

Flip, sort iteration

>>> 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;
Copy after login

break out of the loop

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

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:
Copy after login

else statement in loop

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

    
h
Copy after login

List comprehension-lightweight loop

>>> [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;]
Copy after login

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;
Copy after login

del x and y point to a list at the same time, but deleting x does not will affect y. Only the name is deleted, not the list itself (value)

>>> 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;]
Copy after login

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;]
Copy after login

Note: The namespace is called a scope. Think of it as a place to hold variables, similar to an invisible dictionary. When executing an assignment statement such as x=1, the key x and value 1 are placed in the current namespace. This namespace is generally the global namespace.

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

eval evaluation

>>> 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)
Copy after login

Introduction to conditions, loops, etc. in python


The above is the detailed content of Introduction to conditions, loops, etc. in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template