print 3.0版本要打括号是因为它变成了函数,而在2.0版本时时语句。
赋值技巧
1. 序列解包(sequence unpacking)/可迭代解包
将多个值的序列解开,放到变量的序列中
>>>values=1,2,3
>>>values
(1,2,3)
>>>x,y,z=values
>>>x
1
###############################################################
>>>scoundrel={'name': Robin, 'girlfriend':'Marion'}
>>>key, vlaue=scoundrel,popitem()
>>>key
'girlfriend'
>>>value
'Marion'
3.0版本还可以把最后一个参数写作rest,这样剩余没有分配的元素都会分配到rest里
2. 链式赋值(chained asignment)
将同一个值赋给多个变量的捷径。x=y=somefunction()
3. 增量赋值(augmented assignment)
四则运算和%等标准运算都适用
x+=1 就是 x=x+1
x=2 就是x=x2
x/=1 就是 x=x/1 以此类推
条件和条件语句
False, None,0,"",(),[],{}都会看做是假false,其他都为真。
if condition:
if condition:
do
elif contion:
do
else:
do
else:
do
x is y是两个是同一个对象, x==y是两个对象相等,但是不一定是同一个对象。
assert(断言): 如果为假,报错, 后面可以添加字符串,解释断言,该功能常用在程序中置入检查点。assert 0<age<100, 'The age must be realistic'
循环
while 循环:
name='' "
#还可以用 while not name.strip()
while not name or name.isspace():
name=raw_input("Please enter your name: ')
print 'Hello, %s!' % name
for 循环: (如果能用for尽量不用while)
words=['this', 'is','an','ex','parrot']
for word in words:
print word
range(0,10): 0-9
range(10):0-9
循环遍历字典:
d= {'x':1, 'y':2,'z':3}
for key in d:
print key, 'corresponds to'. d[key]
################################################
for key, value in d.itmes():
print key, 'correspondsto' vlaue
跳出循环
- break 跳出循环
- continue结束当前循环,直接跳到下一轮。
- while True/break: 第一部分负责初始化,第二部分则在循环条件为 真的情况下使用第一部分内初始化好的数据
#-*- coding=utf8 -*-
word="dummy" #哑变量
while word:
word=raw_input("Please enter a word: ")
# 处理word
print 'The word was '+ word
##############################################
while True:
word = raw_input("Please enter a word: ")
if not word: break
#处理word:
print 'The word was ' + word
- 使用else
broke_out = False
for x in seq:
do_something(x)
if condition(x):
broke_out=True
break
do_something_else(x)
if not broke_out:
print "I didn't break out!"
########举例##################
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!"
迭代工具
- 并行迭代。
names=['anne','beth','george','damon']
ages=[12,45,32,102]
####################
for i in range(len(names)):
print names[i], 'is', ages[i], 'years old.'
####################
#用zip将两个列表压缩在一起构成一个个元组,然后在循环中解压元祖
for name,age in zip(names, ages):
print name, 'is', age,'years old'
#zip擅长应付不等长的序列,当最短的序列用完就会停止
- 编号迭代
依据索引迭代
for string in strings:
if 'xxx' in string:
index= strings.index(string) #Search for the string in the list of strings
string[index]='[censored]'
##########################
index=0
for string in strings:
if 'xxx' in string:
strings[index]='[censored]'
index +=1
##########################
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index]='[censored]'
- 翻转和排序迭代
reversed, sorted 函数,作用与任何序列或者可迭代对象上,不是原地修改对象,而是返回翻转或者排序后的版本。 可以在for循环和join中使用,但是不可以直接使用索引,分片,及调用list方法,用list类型转化后就可以了。
列表推导式(轻量循环)list conprehension
[x*x for x in range(10) if x % 3 ==0]
[(x,y) for x in range(3) for y in range(3)]
男孩女孩名字配对练习
girls=['alice', 'bernice', 'clarice']
boys=['chris','arnold','bob']
letter_girl={}
a alice b bernice
for girl in girls:
letter_girl.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys g in letter_girls[b[0]]]
其他
pass: 结合注释扮演文档字符串,注释,代码初期开发时。
del:删除名称
动态创造Python 代码:
- exec:执行语句,不返回对象
结合scope(放置代码字符串命名空间的字典)来保证创造
>>>from math import sqrt
>>>scope={}
>>>exec 'sqrt=1' in scople
>>>sqrt(4)
2.0
>>>scope['sqrt']
1
- eval:计算表达式(以字符串形式书写),返回结果值
>>>eval(raw_input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6+18*2
42
综合使用:
>>>scope={}
>>>scope['x']=2
>>>scope['y']=3
>>>eval('x * y ', scope)
6
#########
>>>scople={}
>>>exec 'x=2' in scope
>>>eval(' x*x', scope)
4