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

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:(一例以蔽之)
name = raw_input('What is your name? ') if name.endswith('Gumby'): if name.startswith('Mr.'): print 'Hello, Mr. Gumby' elif name.startswith('Mrs.'): print 'Hello, Mrs. Gumby' else: print 'Hello, Gumby' else: print 'Hello, stranger'

#比较也可以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循环
name = '' while not name: name = raw_input('Please enter your name: ') print 'Hello, %s!' % name #改进版本为not name.isspace()或者not name.strip(),以避免输入空格

8.for循环
#for each in a List words = ['this', 'is', 'an', 'ex', 'parrot'] for word in words: print word #Actually in a List for number in range(1,101): #range(1,101) == [1,2,...,100] #range(4) == [0, 1, 2, 3] #range(2,10,3) == [2, 5, 8] print number #Iterating Over Dictionaries d = {'x': 1, 'y': 2, 'z': 3} for key in d: #等价于for key in d.keys(): print key, 'corresponds to', d[key] for key, value in d.items(): print key, 'corresponds to', value

9.zip两个序列结对遍历
names = ['anne', 'beth', 'george', 'damon'] ages = [12, 45, 32, 102] for i in range(len(names)): print names, 'is', ages, 'years old'

#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
#一段经典的示例 while True: word = raw_input('Please enter a word: ') if not word: break # do something with the word: print 'The word was ' + word


13.循环中的else分句
from math import sqrt for n in range(99, 81, -1): root = sqrt(n) if root == int(root): print n break else: print "Didn't find it!"


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)]
#最后一段代码的等效代码: result = [] for x in range(3): for y in range(3) result.append((x, y)) 15.pass —— Nothing Happened! if name == 'Ralph Auldus Melish': print 'Welcome!' elif name == 'Enid': # Not finished yet... pass

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

#以下两段示例联合使用exec、eval、名字空间, scope = {} scope['x'] = 2 scope['y'] = 3 eval('x * y', scope) #---> 6 scope = {} exec 'x = 2' in scope eval('x*x', scope) #---> 4

你可能感兴趣的:(Math,list,String,python,input,import)