《Beginning Python From Novice to Professional》学习笔记七:Statement

来源:互联网 发布:扫雷c语言代码 编辑:程序博客网 时间:2024/04/25 16:46
1.More about Print
print 'Age:', 42
---> Age: 42
注意以下语句的区别:
1, 2, 3
---> (1, 2, 3)
print 1, 2, 3
---> 1 2 3
print (1, 2, 3)
---> (1, 2, 3)

2.More about Import
import somemodule
from somemodule import somefunction
from somemodule import somefunction, anotherfunction, yetanotherfunction
from somemodule import *
import math as foobar
foobar.sqrt(4)
from math import sqrt as foobar
foobar(4)

3.赋值
Sequence Unpacking:
x, y, z = 1, 2, 3   #其实质是Tuple到Tuple的赋值
print x, y, z
---> 1 2 3

4.Blocks: The Joy of Indentation(伪代码pseudocode)
this is a line
this is another line:
    this is another block
    continuing the same block
    the last line of this block
phew, there we escaped the inner block
#由第二行的:号开始一段代码块,此段块均必须进行缩进

5.条件语句
在Python中,以下值如使用在Boolean中均被看作False:False、None、0、""、()、[]、{},其它全部被认为是True。
#As Python veteran Laura Creighton puts it, the distinction is really closer to something vs. nothing,
rather than true vs. false.


注意 True + False + 42   ---> 43
bool()可以转换为bool型
bool('I think') ---> True
bool(42)        ---> True
bool('')        ---> False
bool(0)         ---> False
注意  尽管bool([])==False,但[]!=False
#Nested Blocks:(一例以蔽之)


#比较也可以Chained:如 0 < age < 100.
#注意is比较和==比较的区别
x = y = [1, 2, 3]
z = [1, 2, 3]
x == y   ---> True
x == z   ---> True
x is y   ---> True
x is z   ---> False
x is not z ---> False
#is比较看是否相同而非是否相等(The Identity Operator),注意Python中的引用,x、y实际指向同一个List对象,所以x is y,
#而z指向另一个List对象(尽管有相同的值)


6.断言
assert 0 < age < 100                                    #当age不在此范围内时会引起异常
assert 0 < age < 100, 'The age must be realistic'       #后面字符串内的文字会作为异常说明

7.while循环


8.for循环


9.zip两个序列结对遍历

#zip()代码可以实现两个序列结对
zip(names, ages)   #若zip前后的List长度不同,它将会使用最短的结对
---> [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
#因此以下代码可实现等价功能
for name, age in zip(names, ages):
    print name, 'is', age, 'years old'

10.enumerate带下标遍历
首先介绍一下enumerate()函数,如何s是Iteratable的,则enumerate(s)会生成一个遍历对象
s=list('thy')   ---> ['t', 'h', 'y']
list(enumerate(s))
---> [(0, 't'), (1, 'h'), (2, 'y')]
for index, string in enumerate(strings):
    if 'xxx' in string:
        strings[index] = '[censored]'

11.sorted和reversed遍历
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!'))   #reversed生成的只是一个遍历对象,而非List
---> ['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
''.join(reversed('Hello, world!'))
---> '!dlrow ,olleH'

12.跳出循环
break, continue


13.循环中的else分句


14.List Comprehension—Slightly Loopy
#从其它List中生成List的方法
[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)]

16.del删除对象
x = ["Hello", "world"]
y = x
y[1] = "Python"   #注意y对赋值同时影响了x
x   --->['Hello', 'Python']
#但是接着
del x  #删除x却不会影响y,
      #The reason for this is that you delete only the name, not the list itself (the value).
       #In fact, there is no way to delete values in Python
y   ---> ['Hello', 'Python']

17.exec与eval
#exec运行String中的语句Python statements
from math import sqrt
scope = {}
exec 'sqrt = 1' in scope   #这样sqrt的影响被限制在scope中,否则下句的sqrt将被覆盖而无法运行
sqrt(4)   ---> 2.0
scope['sqrt']   ---> 1
#现在scope将会保存两个项,一项key为'__builtins__',包含了所有的内置函数和值。
#另一项则为'sqrt': 1。

#eval会计算String中的表达式Python expression并返回结果

eval(raw_input("Enter an arithmetic expression: "))
---> Enter an arithmetic expression: 6 + 18 * 2
---> 42