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

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

>>> x={‘a’:1,’b’:2}
>>> key,value=x.popitem()
>>> key,value
(‘a’, 1)
>>> del x[key]
traceback (most recent call last):
file “”, line 1, in
del x[key]
keyerror: ‘a’
>>> x
{‘b’: 2}
>>> x[key]=value
>>> x
{‘a’: 1, ‘b’: 2}
>>> del x[key]

增量赋值

>>> x=2
>>> x+=1
>>> x*=2
>>> x
>>> fnord=’foo’
>>> fnord+=’bar’
>>> fnord*=2
>>> fnord
‘foobarfoobar’

条件执行if语句

>>> name=raw_input(‘?’)
?yq z
>>> if name.endswith(‘z’): \
print ‘hello,mr.z’
hello,mr.z

else子句

>>> name=raw_input(‘what is your name?’)
what is your name?yq z
>>> if name.endswith(‘z’):
print ‘hello,mr.z’
else:
print ‘hello,stranger’
hello,mr.z

elif子句

>>> num=input(‘enter a number: ‘)
enter a number: 5
>>> if num>0:
print ‘the number is position’
elif num>> name=raw_input(‘what is 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 10:’)
enter a number between 1 and 10:6
>>> if number=1:
print ‘great!’
else:
print ‘wrong!’
great!>>> age=10
>>> assert 0>> age=-1
>>> assert 0″, line 1, in
assert 0

while循环

>>> x=1
>>> while x>> while not name:
name=raw_input(‘please enter your name:’)
print ‘hello,%s !’ % name
please enter your name:zyq
hello,zyq !

for循环

>>> words=[‘this’,’is’,’an’,’ex’,’parrot’]
>>> 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={‘x’:1,’y’:2,’z’:3}
>>> for key in d:
print key,’corresponds to’,d[key]
y corresponds to 2
x corresponds to 1
z corresponds to 3

并行迭代

>>> 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 12 years old
beth is 19 years old
george is 18 years old
damon is 20 years old>>> zip(names,ages)
[(‘anne’, 12), (‘beth’, 19), (‘george’, 18), (‘damon’, 20)]
>>> for name,age in zip(names,ages):
print name,’is’,age,’years old’
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=[‘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函数提供索引-值对
if ‘h’ in s2:
s[index]=’df’
>>> s
[‘df’, ‘df’, ‘olm’, ‘piy’]

翻转、排序迭代

>>> 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跳出循环

>>> 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
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 ‘h’
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=[‘alice’,’bernice’,’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’:
#还没完
pass
elif name==’bill’:
print ‘access denied’
else:
print ‘nobody!’

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

>>> 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 last):
file “”, line 1, in
sqrt(4)
typeerror: ‘int’ object is not callable
#增加一个字典,起到命名空间的作用
>>> from math import sqrt
>>> scope={}
>>> exec ‘sqrt=1’ in scope
>>> sqrt(4)
2.0
>>> scope[‘sqrt’]

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

>>> len(scope)2
>>> scope.keys()
[‘__builtins__’, ‘sqrt’]

eval 求值

>>> scope={}
>>> scope[‘x’]=2
>>> scope[‘y’]=3
>>> eval(‘x*y’,scope)
>>> scope={}
>>> exec ‘x=2’ in scope
>>> eval(‘x*x’,scope)

以上就是python中条件、循环等介绍说明的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论