Gets any key-value pairs in the dictionary
>>> x={' A ': 1, ' B ':2}>>> key,value=x.popitem () >>> key,value (' A ', 1) >>> del X[key] Traceback (most recent): File "<pyshell#16>", line 1, in <module> del x[key]keyerror: ' A ' &G t;>> x{' B ': 2}>>> x[key]=value>>> x{' a ': 1, ' B ': 2}>>> del X[key]
Increment assignment
>>> x=2>>> x+=1>>> x*=2>>> x>>> fnord= ' foo ' >>> fnord+= ' bar ' >>> fnord*=2>>> fnord ' Foobarfoobar '
Conditional execution if statement
>>> name=raw_input ('? ')? Yq z>>> if Name.endswith (' Z '): \ print ' Hello,mr.z ' Hello,mr.z
ELSE clause
>>> Name=raw_input (' What's your name? ') What is your name? Yq z>>> if Name.endswith (' Z '): print ' hello,mr.z ' else: print ' Hello,stranger ' hello,mr.z
elif clause
>>> num=input (' Enter a number: ') Enter a number:5>>> if num>0: print ' The number is position ' Eli F num<0: print ' The number is negative ' else: print ' The number was zero ' the number is position
Conditional nested statements
>>> Name=raw_input (' What's your name? ') What is your name? Yq z>>> 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
>>> number=input (' Enter a number between 1 and: ') Enter a number between 1 and 10:6>>> if number<=1 0 and Number>=1: print ' great! ' else: print ' wrong! ' great!
>>> age=10>>> assert 0<age<100>>> age=-1>>> assert 0<age< 100Traceback (most recent): File ' <pyshell#21> ', line 1, in <module> assert 0<age< 100AssertionError
While loop
>>> x=1>>> while x<=100: print x x+=1
>>> While not name: name=raw_input (' Please enter your name: ') print ' hello,%s! '% name Your NAME:ZYQHELLO,ZYQ!
For loop
>>> words=[' This ', ' was ', ' an ', ' ex ', ' Parrot ']>>> for word in words: print word Thisisanexparrot>>> Range (0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> for I in Range (1,8): print i246
Dictionary loops (iterations)
>>> d={' x ': 1, ' Y ': 2, ' Z ':3}>>> for key in D: print key, ' corresponds to ', D[key] y corresponds to 2x corresponds to 1z corresponds to 3
Parallel iterations
>>> names=[' Anne ', ' Beth ', ' George ', ' Damon '] >>> ages=[12,19,18,20]>>> for I in range ( Len (names)): print names[i], "is", ages[i "," years old "Anne is" years Oldbeth is "years Oldgeorge is years ol Ddamon is-years old
>>> Zip (names,ages) [(' Anne ', ' + '), (' Beth ', +), (' George ', '), (' Damon ', ')]>>> for name,age in Zip (NA mes,ages): print name, ' is ', age, ' years-old ' Anne is- years Oldbeth is years Oldgeorge-is-years Olddamon is Years old>>> Zip (range (5), xrange (100)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
Numbering iterations
>>> d[1, 2, 4, 4]>>> for x in D: if x==4: d[d.index (x)]=6 >>> d[1, 2, 6, 6]>> > s=[' skj ', ' Kiu ', ' Olm ', ' Piy ']>>> index=0>>> for S1 in S: if ' K ' in S1: s[index]= ' HH ' Index+=1 >>> s[' hh ', ' hh ', ' Olm ', ' Piy ']>>> for INDEX,S2 in Enumerate (S): #enumerate函数提供索引-value pairs if ' H ' in S2: s[index]= ' DF ' >>> s[' df ', ' df ', ' Olm ', ' Piy ']
Flipping, sorting iterations
>>> sorted ([4,3,6,8,3]) [3, 3, 4, 6, 8]>>> sorted (' hello,world! ') ['! ', ', ', ' H ', ' d ', ' e ', ' l ', ' l ', ' l ', ' o ', ' o ', ' R ', ' W ']>>> list (reversed (' hello,world! ')) ['! ', ' d ', ' l ', ' r ', ' O ', ' w ', ', ', ' o ', ' l ', ' l ', ' e ', ' H ']>>> '. Join (Reversed (' hello,world! ')) '! Dlrow,olleh '
Break jumps out of the loop
>>> 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 (' Please enter a word: ') if not word:break print ' The word was ' +word< C7/>please Enter a word:fthe word was fplease enter a word:
Else statement in the loop
>>> for N in range (99,81,-1): m=sqrt (n) if M==int (m): print M breakelse: print ' h ' h
List derivation-lightweight loops
>>> [x*x for x in range (][0), 1, 4, 9, +, +, $, $, a, 81]>>> [x*x for x in range] if x%3==0][0 , 9, 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), 0), (2, 1), (2, 2)]>>> result=[]>>> for x in range (3): For y in range (3): Result.append ((x, y)) &G t;>> result [(0, 0), (0, 1), (+ 0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]>>> girls=[' Alice ', ' Ber Nice ', ' Clarice ']>>> boys=[' Chris ', ' Arnold ', ' Bob ']>>> [B + ' + ' +g for B in boys for g in girls if b[0]==g[0] [' Chris+clarice ', ' arnold+alice ', ' Bob+bernice ']
Pass
>>> if name== ' NSDs ': print ' welcome! ' Elif name== ' UK ': #还没完 passelif name== ' Bill ': print ' Access Denied ' else: print ' nobody! '
del X and Y point to a list at the same time, but deleting x does not affect Y. Delete only the name, not the list itself (value)
>>> x=[' hello ', ' World ']>>> y=x>>> y[1]= ' python ' >>> x[' hello ', ' python ']>> > del x>>> y[' Hello ', ' Python ']
Exec
>>> exec "print ' hello,world! '" hello,world!>>> from math import sqrt>>> exec "sqrt=1" >>> sqrt (4) Traceback (most recent call L AST): File "<pyshell#36>", line 1, in <module> sqrt (4) TypeError: ' int ' object was not callable# add a dictionary , play the role of the namespace >>> from math import sqrt>>> scope={}>>> exec ' sqrt=1 ' in scope>>> sqrt (4) 2.0>>> scope[' sqrt ']
Note: namespaces, called scopes. You can think of it as a place to save variables, similar to an invisible dictionary. When you execute an assignment such as x=1, the key x and value 1 are placed in the current namespace, which is generally the global namespace.
>>> len (Scope) 2>>> Scope.keys () [' __builtins__ ', ' sqrt ']
Eval evaluation
>>> scope={}>>> scope[' x ']=2>>> scope[' y ']=3>>> eval (' x*y ', scope) >>> scope={}>>> exec ' x=2 ' in scope>>> eval (' x*x ', scope)