04-条件、循环和其它语句

来源:互联网 发布:郝蕾 少年天子 知乎 编辑:程序博客网 时间:2024/05/28 15:39

赋值魔法

1.序列解包(sequence unpacking)

序列解包也称递归解包:将多个值的序列解开,然后放到变量的序列中,只需要一个表达式就可以完成同时为多个变量赋值的操作。

# 1>给多个变量一次赋值>>> x,y,z = 1,2,3>>> print x,y,z1 2 3  # 2>交换变量的值--相比C语言真的方便不要太多吧>>> x,y=y,x>>> print x,y,z2 1 3## 上面的这些操作方法就是赋值的序列解包操作# 3.更形象的表示方法好比下面这个案例:>>> values =1,2,3>>> values(1,2,3)>>> x,y,z=values>>> x1

**总结:**Python 赋值语句序列解包,必须保证解包的序列元素数量和=等号左边的变量数量相等,如果不一致python在赋值时会引发错误异常。

2.链式赋值(chained assignment)

将一个值赋值给多个变量的捷径。

x=y=1

3.增量赋值(augmented assigment)

一般不写成这种形式x=x+1

>>> x = 2>>> x += 1>>> x *=2>>> x6

对于其他数据类型也适用

>>> fnord = 'foo'>>> fnord += 'bar'>>> fnord *=2>>> fnord'foobarfoobar'

条件和条件语句

布尔变量

真值(布尔值)
下面的值在作为布尔表达式的时候,会被解释器看做假(false).

False None 0 “” () [] {}

条件执行和if语句

name =raw_input(‘What’s your name?’)
if name.endswith(‘Gumby’)
print ‘Hello,Mr.Gumby’
if语句可以试下条件执行

else子句

elif子句

嵌套代码块

更复杂的条件

1.比较运算符

2.相等运算符

3.is:同一运算符

is运算符是判定同一性而不是相等性。

>>>x =[1,2,3]>>>y= [2,4]>>> x is not yTrue>>> del x[2]>>> y[1] = 1>>> y.reverse()>>> x==yTrue>>> x is yFalse

总结:使用==运算符来断定两个对象是否相等,使用is断定两者是否等同(同一对象)。

4.in:成员资格运算符

name = raw_input("What's your name?")if 's' in name:    print "'s' is in your name!"

5.字符串和序列比较

可以按照字母顺序排列进行比较

>>>'a' < 'b'hcTrue

6.布尔运算符

or和and运算符

7.断言

用伪代码实现有点类似:

if not condition:

crash program
其实这个用if else语句也可以实现

age =-1assert 0<age<100,'the augument must be realistic'

循环

1.while循环

x = 1while x<10:    print x    x += 1

2.for循环

  • 如果能使用for循环,就尽量不用while循环。
#for循环遍历列表words = ['this','is','an','ex','parrot']for word in words:    print word

范围函数

>>> range(0,3)[0, 1, 2]>>> range(3)[0, 1, 2]

3.循环遍历字典元素

d = {'x': 1,'y': 2,'z': 3}for key in d:    print key,d[key]

键-值

for key,value in d.items():    print key,value

4.一些迭代工具

1.并行迭代

>>> names=['anne','beth','george','damon']>>> ages=[12,45,32,102]>>> for i in range(len(names)):>>>    print names[i],'is',ages[i]anne is 12beth is 45george is 32damon is 102

zip压缩

>>> zip(names,ages)[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]# 产生坐标>>> zip(range(5),xrange(10000))[(0,0),(1,1),(2,2),(3,3),(4,4)]

2.按索引迭代

>>> L = ['Adam', 'Lisa', 'Bart', 'Paul']>>> for index, name in enumerate(L):>>> index, '-', name0 - Adam1 - Lisa2 - Bart3 - Paul

enumerate()函数把[‘Adam’, ‘Lisa’, ‘Bart’, ‘Paul’]变为[(0, ‘Adam’), (1, ‘Lisa’), (2, ‘Bart’), (3, ‘Paul’)]因此,迭代的每一个元素实际上是一个tuple:

for t in enumerate(L):
index = t[0]
name = t[1]
print index, ‘-‘, name

如果我们知道每个tuple元素都包含两个元素,for循环又可以进一步简写为:

for index, name in enumerate(L):
print index, ‘-‘, name

这样不但代码更简单,而且还少了两条赋值语句。

3.翻转和排序迭代

sorted方法返回列表:

sorted([2,3,1,4])
[1, 2, 3, 4]

reversed方法返回一个可迭代对象:

reversed([2,3,1,4])输出:<listreverseiterator at 0xb1afda0>

5.跳出循环

1.break

for i in range(0,10):    if i < 8:        print 'i=',i    else:        break

2.continue

跳过剩余的循环体,但是不结束循环.

>>> for letter in 'Python':     # 第一个实例>>>   if letter == 'h':>>>      continue>>> '当前字母 :', letter当前字母 : P当前字母 : y当前字母 : t当前字母 : o当前字母 : n

3.while True/break习语

>>> while True:>>>     word = raw_input('please enter a word:')>>>     if not word: break>>>     'The word was '+ word

4.循环中的else子句

在循环中增加一个else子句-它仅在没有调用break时执行

from math import sqrtfor n in range(88,81,-1):    root =sqrt(n)    if root == int(root):        print n        breakelse:    print 'Don\'t find it!'

6.列表推导式-轻量级循环

列表式推导式利用其他列表创建新列表(类似于数学语中的集合推导)的一种方法。

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

7.三人行

  • pass语句什么都不做,可以作为占位符使用。
  • del语句用来删除变量,或者数据结构的一部分,但是不能删除值。
  • exec语句用于执行Python程序相同的方法来执行字符串。
  • eval函数对写在字符串中的表达式进行计算并且返回结束。

pass

python中空代码块是非法的,正确的使用方法是在语句中加上pass。

name ='bob1'if name == 'bob':    passelse:    print 'You are wrong!'

del

del会删除那些不在使用的对象

>>> x=1>>> del x>>> xTraceback (most recent call last):  File "<ipython-input-23-401b30e3b8b5>", line 1, in <module>    xNameError: name 'x' is not defined

删除的只是名称,而不是列表本身(值)。在Python中没有办法删除值(也不需要过多考虑删除值的问题,因为在某个值不在使用的时候,Python解释器会负责内存的回收)

exec

exec语句用来执行储存在字符串或文件中的Python语句。例如,我们可以在运行时生成一个包含Python代码的字符串,然后使用exec语句执行这些语句,下面是一个简单的例子。

>>> exec 'print "Hello World"'Hello World

这里有个scope(命名空间,作用域)的概念,为了不破坏现在的scope,可以新建一个scope(一个字典)执行exec(Javascript没有此功能):

>>> scope = {}>>> exec("a = 4", scope)>>> a2>>> scope['a']4>>> scope.keys()dict_keys(['a', '__builtins__'])

builtins包含了所有的内建函数和值;

而普通的{}不会包含builtins

>>> a = {}>>> a.keys()dict_keys([])

eval

同exec一样,eval也可以使用命名空间:

>>> result = eval('2+3')>>> result5>>> scope={}>>> scope['a'] = 3>>> scope['b'] = 4>>> result = eval('a+b',scope)>>> result7
0 0