print和import
>>> print 'age:',42 #用逗号分隔多输出 age: 42 >>> print 'Hello,' + 'world!' #用'+'连接字符串输出 Hello,world! >>>
import
>>> import string #导入模块
>>>
>>> from math import sqrt #导入模块中的函数
>>>
>>> from math import * # 导入模块中的所有函数
>>>
>>> import math as foobar #导入模块并重命名
>>>
>>> from math import sqrt as foobar #导入模块中的函数并重命名
>>>
对于两个模块有同名函数的情况,可以采用第一种和最后一种导入方式:
>>>module1.function(...) #用第一种方式导入,用模块调用函数
>>>module2.function(...)
>>>
>>>from module1 import function as func1 #用最后一种方式导入,为函数重命名,可直接用别名调用
>>>from module2 import function as func2
>>>
赋值
序列解包
>>> x,y,z = 1,2,3 #序列解包或递归解包,将多个值的序列解开,然后放到变量的序列中;两段代码等价
>>> print x,y,z #这一点可以实现函数或方法返回多个值,因为函数或方法可以返回元组,可以用多个变量接收元组中的值
1 2 3 #注意:‘=’两侧的元素和变量个数要相等
>>>
>>> values = 1,2,3
>>> values
(1, 2, 3)
>>> x,y,z = values
>>> print x,y,z
1 2 3
>>>
链式赋值
>>> x = y = 1
>>> x
1
>>> y
1
>>>
增量赋值
用 +=、-=、*=、/=等组合运算符赋值
>>> x = 1
>>> x
1
>>> x += 1 #等价于 x = x + 1
>>> x
2
>>>
语句块
Python用缩进表示语句块(一般缩进为4个空格)this is a line
this is another line
this is a block
continuing the same block
the last line of this block
there we escaped the inner block
条件和条件语句
简单判断语句
if 条件: #当条件为真时,条件语句执行,判断语句结束;全部条件都为假时,执行else:后的语句
条件语句
:
elif 条件:
条件语句
:
...
else:
语句
真值(布尔值):True和False
真值为False的有:False、None、0、""、()、[]、{} 。 False默认值为0。
真值为True的有:除False外。 True 默认值为1。
bool函数(类型)
>>> bool(42)
True
>>> bool(0)
False
>>> bool('')
False
>>> bool('Hello')
True
>>>
嵌套代码块
if 条件:
if 条件:
条件语句
:
elif 条件:
条件语句
:
...
else:
语句
:
elif 条件:
语句
:
...
else:
语句
:
条件:可返回布尔值的表达式
比较运算符
相等运算符
is:同一性运算符
in:成员资格运算符
字符串和序列比较
布尔运算符(逻辑运算符)
断言
如果需要确保程序中的某个条件为真程序才正常工作的话,断言(assert语句)就很有用。条件后可以添加字符串,用来解释断言。
>>> age = -1
>>> assert 0<age<100,'The age must be realistic'
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
assert 0<age<100,'The age must be realistic'
AssertionError: The age must be realistic
>>>
循环
while循环
for循环
一些迭代工具
并行迭代
按索引迭代
翻转和排序迭代
跳出循环
break
continue
while True/break习语
循环中的else子句
from math import sqrt #仅当break没执行时,执行else子句
for n in range(99,81,-1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!"
列表推导式——轻量级循环
列表推导式(list comprehension)是利用其他列表创建心列表的一种方法。工作方式类似于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]
>>>
pass,del和exec语句
pass
pass语句什么也不做,做占位符用。
del
del语句可以删除一个对象的引用,不能删除对象本身。当该对象无引用时,Python解释器的垃圾收集功能自动删除。Python解释器会负责内存的回收。
exec和eval
>>> exec "print 'Hello,world!'" #exec执行一个字符串的语句
Hello,world!
>>>
>>> eval('1+2') #eval计算以字符串形式书写的Python表达式,并返回结果值
3
>>>