《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:(一例以蔽之)


#比较也可以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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Gain a fundamental understanding of Python’s syntax and features with the second edition of Beginning Python, an up–to–date introduction and practical reference. Covering a wide array of Python–related programming topics, including addressing language internals, database integration, network programming, and web services, you’ll be guided by sound development principles. Ten accompanying projects will ensure you can get your hands dirty in no time. Updated to reflect the latest in Python programming paradigms and several of the most crucial features found in the forthcoming Python 3.0 (otherwise known as Python 3000), advanced topics, such as extending Python and packaging/distributing Python applications, are also covered. What you’ll learn * Become a proficient Python programmer by following along with a friendly, practical guide to the language’s key features. * Write code faster by learning how to take advantage of advanced features such as magic methods, exceptions, and abstraction. * Gain insight into modern Python programming paradigms including testing, documentation, packaging, and distribution. * Learn by following along with ten interesting projects, including a P2P file–sharing application, chat client, video game, remote text editor, and more. Complete, downloadable code is provided for each project! Who is this book for? Programmers, novice and otherwise, seeking a comprehensive introduction to the Python programming language. About the Apress Beginning Series The Beginning series from Apress is the right choice to get the information you need to land that crucial entry–level job. These books will teach you a standard and important technology from the ground up because they are explicitly designed to take you from “novice to professional.” You’ll start your journey by seeing what you need to know—but without needless theory and filler. You’ll build your skill set by learning how to put together real–world projects step by step. So whether your goal is your next career challenge or a new learning opportunity, the Beginning series from Apress will take you there—it is your trusted guide through unfamiliar territory!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值