`

python学习笔记6——第五章 条件、循环和其他语句

阅读更多

第五章 条件、循环和其他语句

 

注意:注意代码的缩进,否则会报错,因为是通过缩进来区分代码块的。用Tab或者两个空格或四个空格,但应保持一致,不要混用,决定用tab键方便。

 

1. ","  连续输出,以空格分隔

>>> print 'Age',42
Age 42

#
>>> for i in range(10):   
	print i,        #语句以逗号结尾,print语句会在一行内打印,并以空格分开;若无逗号,则分行打印

	
0 1 2 3 4 5 6 7 8 9

 

   不需使用格式化字符%,更加方便

>>> a = '1'
>>> b = '2'
>>> c = '3'
>>> print a,b,c
1 2 3

 

   使用print时,以","隔开,不能组成元组。而不用print以逗号隔开,则是一个元组

>>> print 1,2,3   #打印以空格隔开的数字
1 2 3
>>> 1,2,3    #元组
(1, 2, 3)
>>> print (1,2,3)   #打印元组
(1, 2, 3)

 

2. import

 

   一般格式:

   import module
   from module import function1, function2

   from module import*

   还可以使用as来进行重命名,解决不同模块,相同函数名问题。

>>> import math as m
>>> m.sqrt(4)
2.0
>>> from math import sqrt as s
>>> s(4)
2.0

 

3. 赋值

   多个赋值操作同时进行

>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
 

   两个元素值交换(很简单)

>>> x,y,z = 1,2,3
>>> x,y = y,x
>>> print x,y,z
2 1 3

 

   序列解包:将多个值的序列解开,放到变量的序列中

>>> x,y,z = (1,2,3)
>>> x
1

 

   当函数或方法返回元组时,很有用

>>> d = {'a':'1','b':'2'}
>>> key, value = d.popitem()   #popitem()随机弹出一组键值对,并解包分别赋值
>>> key
'a'
>>> value
'1'

 

   注意 “=”两边元素数量需要相等,否则报错。

 

4. 链式赋值 x = y = somefunction(),引用相同,与x=somefunction(),y =somefunction()不一定相同

    三元运算: a if b else c,如果b为真则返回b赋值给a,若b为假,则返回c值赋值给a

 

5. if something: do something

    elif something: do something

    else: do something

    注意冒号(:),以及elif

 

6. is(is not)判断同一性,==判断相等性

>>> x = y = [1,2,3]    #x和y绑定到同一列表
>>> z = [1,2,3]          #z绑定到一个新的列表
>>> x == y                #值相等
True
>>> x == z                #值相等
True
>>> x is y                    #x和y是同一个对象
True
>>> x is z                   #x和z不是同一个对象
False

 

7. 断言assert——在错误条件出现时,直接让程序崩溃

>>> age = -1
>>> assert 0 < age < 100

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    assert 0 < age < 100
AssertionError
>>> 
>>> #也可以添加字符串来解释断言
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'

Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    assert 0 < age < 100, 'The age must be realistic'
AssertionError: The age must be realistic
 

8. while & for——能用for,尽量不用while

   注意:别漏掉冒号(:);输入完成后,需按两次回车程序才能运行

   while

>>> x = 1
>>> while x <= 100:
	print x
	x += 1

 

    for

>>> words = ['Hello', 'world']
>>> for word in words:
	print word

#结果
Hello
world

 

   range()迭代某范围内的数字,range(a,b)包括a,不包含b; range(b),从0到b-1

   xrange()类似range(),但range()一次创建整个序列,而xrange一次创建一个数,当迭代大序列时,xrange效率高

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for n in range(5):
	print n

#结果	
0
1
2
3
4

 

   for遍历字典

>>> d = {'a':'1','b':'2','c':'3'}
>>> for key in d:
	print key, 'corresponds to', d[key]

#结果
a corresponds to 1
c corresponds to 3
b corresponds to 2
>>> 
>>> for key, value in d.items():      #>>> d.items()  #将键值对作为元组返回
	print key, 'corresponds to', value    #[('a', '1'), ('c', '3'), ('b', '2')]

#结果	
a corresponds to 1
c corresponds to 3
b corresponds to 2
 

9. 迭代工具

(1)并行迭代——zip()

    例1(1)通常情况

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

#结果	
anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old

 

   例1(2)另一种简单方法,zip(),将两个序列压缩在一起,返回元组列表

>>> zip(names, ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
>>> for name, age in zip(names, ages):  #这句话等同于1(1)的效果
	print name, 'is', age, 'years old'

#结果	
anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old

 

   zip()可以将任意多序列压缩,更特别的是,这些序列的长度可以不同,按最短序列来进行压缩

>>> zip(range(5), xrange(1000000000)) #若xrange改为range会花费很长的时间
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] #range会计算所有的数字,而xrange只需计算前五个数字

 

(2)编号迭代——enumerate()

   通常方法

#找到‘xxx’并修改为‘yyy’
>>> strings = ['xxx', 'is', 'a', 'doctor']
>>> index = 0
>>> for s in strings:
	if 'xxx' in s:          #注意是s而不是strings
		strings[index] = '[yyy]'
	index += 1

	
>>> strings
['[yyy]', 'is', 'a', 'doctor']

 

   简单方法——enumberate()

>>> strings = ['xxx', 'is', 'a', 'doctor']
>>> for index, s in enumerate(strings):
	if 'xxx' in s:
		strings[index] = 'yyy'

		
>>> strings
['yyy', 'is', 'a', 'doctor']

 

(3)翻转和排序迭代——reversed()和sorted(),对副本进行修改,原对象不变

>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> 
>>> reversed('Hello, world!')   #返回对象
<reversed object at 0x01F14770>
>>> list(reversed('Hello, world!'))   #将对象转为列表
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
 

10. 带有步长的range(),用来跳过某些数字,或逆序

>>> range(0, 10, 2)
[0, 2, 4, 6, 8]
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

 

11. while、break

>>> while True:    #采用True
	word = raw_input('Please enter a word: ')
	if not word: break     #当用户不输入是,word为空,所以为false
	print 'The word was', word

	
Please enter a word: test
The word was test
Please enter a word: 
>>> 

 

12. for、break、else

>>> from math import sqrt
>>> for n in range(99, 81, -1):  #99~80,不包括81
	root = sqrt(n)
	if root == int(root):
		print n
		break
else:        #只有当break不执行时,才执行else
	print "Didn't find it!"

#结果	
Didn't find it!

 

13. 列表推导式——利用其他列表创建新列表

   类似for循环

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

 

   多个for

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

 

   多个for+if条件

>>> girls = ['alice', 'bernice', 'clarice']
>>> boys = ['chris', 'arnold', 'bob']
>>> [b + '+' + g for b in boys for g in girls if b[0] == c[0]]

 

14. pass、del、exec和eval

   (1)pass 什么也不做

>>> name = 'd'
>>> if name == 'a':
	print '1'
elif name == 'b':
	#未完成
	pass
else:
	print '3'

	
3
 

   (2)del

   a和b绑定到同一字典,但a赋值为None时,b仍指向那个字典,a = None,只是消除了引用,即a不再指向字典,字典还在,b仍然指向字典。而b = None,将b的引用也消除,此时字典漂浮在内存中,没有名字绑定在它上面,python解释器自动删除。但是,名字a和b仍存在

>>> b = a = {'a':1, 'b':2, 'c':3}
>>> a = None
>>> b
{'a': 1, 'c': 3, 'b': 2}
>>> b = None

 

   del不仅删除引用,也删除名字,但原对象不会被删除,也无法手动删除只有当原对象不再被使用时,python解释器才会自动回收

>>> x = ["Hello", "world"]
>>> y = x
>>> y[1] = "Python"
>>> x   #可以修改
['Hello', 'Python']
>>> del x #删除x,只是将x的引用和x名字删除,而原来的列表不便无法删除,
                 #实际上不需要人为删除,当不用时python解释器会自动回收
>>> x

Traceback (most recent call last):
  File "<pyshell#110>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>> y
['Hello', 'Python']

 

   (3)exec——执行字符串语句(执行一系列python语句)

>>> exec "print 'Hello world!'"
Hello world!

 

    有时会造成干扰

>>> from math import sqrt
>>> exec "sqrt = 1"    #将sqrt当成一个变量执行
>>> sqrt(4)            #sqrt()函数与sqrt变量冲突

Traceback (most recent call last):
  File "<pyshell#118>", line 1, in <module>
    sqrt(4)
TypeError: 'int' object is not callable

 

   解决方法,使用命名空间——通过增加in <scope>来实现

   使得潜在的破坏性代码不会覆盖原函数sqrt,原函数仍能继续工作,而通过exec赋值的sqrt变量只能在作用域中有效

>>> from math import sqrt
>>> scope = {}   #命名空间
>>> exec 'sqrt = 1' in scope  #使用命名空间
>>> sqrt(4)   #原sqrt()方法可继续使用
2.0
>>> scope['sqrt']  #exec执行的sqrt变量赋值仍可用
1

 

   (4)eval类似exec——但是执行Python表达式

>>> eval(raw_input("Enter an arithmetic expression: "))  #类似input()
Enter an arithmetic expression: 6 + 2 *3
12

 

总结:注意链式赋值,del只删除名字和引用,多个变量同时赋值:x,y = (2,3);推导式赋值 [x*x for x in range(10) if x%3 == 0];缩进。

 

用到的函数

(1)chr(n),返回n的所代表的包含一个字符的字符串,0<=n<256,不太懂??
       >>> chr(1)
       '\x01'

(2)eval()

(3)enumerate(seq)产生用于迭代的对

>>> for index, s in enumerate(['a', 'b', 'c']):
	print 'strings[%s] = %s' %(index,s)

	
strings[0] = a
strings[1] = b
strings[2] = c

 (4)ord(c)返回单字符的int值

>>> ord('a')
97

 (5)range([from,]to,[step])创建整数列表  xrange()一次一个整数用于迭代

 (6)reversed(seq) 逆序

 (7)sorted(seq[,cmp][,key][,reverse])排序

 (8)zip(seq1[,seq2.....])创造用于并行迭代的新序列

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics