SqLer

导航

Python 学习---------Day4

第十章 Python语句简介
Python的代码书写要求,以及换行等
语句可以扩越多行,只要将其封闭在圆括号内,方括号内或大括号内即可,可以使用分号终止.
用\可以允许我们跨越多行
一个简单的交互式循环
while True:
input=raw_input("Please input text")
if input=='stop':
break
print input.upper()

while True:
input=raw_input("Please input text:")
if input=='stop':
break
elif not input.isdigit():
print 'bad'*5
else:
print int(input)**2
print bye

while True:
reply=raw_input('Enter text:')
if input=='stop':
break
try:
num=int(input)**2
except:
print 'bad'*8
else:
print num
print 'bye'

第十一章 赋值,表达式和打印
赋值语句
赋值语句建立对象引用值
变量名在首次赋值时候会被创建
变量名在引用前必须先赋值
隐式赋值语句
赋值语句形式
spam='spam'
spam,ham='yum','YUM'
[spam,ham]=['yum','YUM']
a,b,c,d='spam'
spam=ham='lunch'
spams+=42
多目标赋值以及共享引用时候
注意引用的对象是可变还是不可变
变量命名规则 通用
以单一下划线开头的变量名不会被from module import *语句导入
前后有下划线的变量名是系统定义的变量名,对解释器有特殊意义
以两下划线开头,但结尾没有两个下划线的变量名,是类的本地变量
通过交互模式运行时候 只有单个下划线的变量名会保存最后表达式的结果
重定向输出流
print x
等价于
import sys
sys.stdout.write(str(x)+'\n')

import sys
sys.stdout=open('log.txt',a)
...
print x,y,z

log=open('log.txt','w')
print>>log,1,2,3
print>>log,4,5,6
log.close()

第十二章 if测试
通用格式
if:

elif:

else:
字典默认get
branch={'soam':1.25,
'ham':1.99,
'eggs':0.99}
print branch.get('ham','bad')
print branch.get('eggs','bad')
真值测试
2 and 3,3 and 2
返回(3,2)
因为第一行的操作数都是真,所以Python会计算两侧,并返回右侧的对象,在第二个测试中,左侧的操作数为假,所以Python会在该处停止并将其返回作为测试结果
if/else三元表达式
A=Y if X else Z

第十三章 while和for循环
while循环
例子
x='spam'
while x:
print x,
x=x[1:]

a=0;b=10
while a<b:
print a,
a+=1

break 跳出最近所在的循环
continue 调到最近所在循环开头处
pass 什么事也不做,空占位语句
循环else块
只有当循环正常离开时候才会执行

while x
if match(x[0]):
print 'ni'
break
x=x[1:]
else:
print 'not found'

while True:
x=next()
if not x:break
....

x=1
while x:
x=next()
if x:
...
x=next()
while x:
...
x=next()

for循环
for x in ['spam','eggs','ham']:
print x,

sum=0
for x in [1,2,3,4]:
sum=sum+x

prod=1
for item in [1,2,3,4]:
prod*=item

s='lumberjack'
t=('and','I\'m','okay')
for x in s:
print x,
for x in t:
primt x,

在for循环中的元组赋值
T=[(1,2),(3,4),(5,6)]
for (a,b) in T:
print a,b

items=['aaa',111,(4,5),2.01]
tests=[(4,5),3.14]
for key in tests:
for item in items:
if item==key:
print key,"was found"
break
else:
print key,"not found"

文件扫描
file=open('test.txt','r')
print file.read()

file=open('text.txt')
while True:
line=file.readline()
if not line:
break
print line,

file=open('test.txt','rb')
while True:
chunk=file.read(10)
if not chunk:
break
print chunk,

for line in open('test.txt').readline():
print line

迭代器
for x in [1,2,3,4]:
print x**2
for x in (1,2,3,4):
print x**3,
for x in 'spam':
print x*2,
文件迭代器
f=open('test.py')
f.readline()
f.eardline()

f=open('test.py')
f.next()
f.next()

for line in open('test.txt'):
print line.upper()

迭代器在Python中是以C语言的速度运行的,而while循环是通过Python虚拟机器运行Python字节码的.

其他内置类型迭代器
L=[1,2,3]
I=iter(L)
I.next()
I.next()

D={'a':1,'b':2,'c':3}
for key in D.keys():
print key,D[key]

for key in D:
print key,D[key]

字典有一个迭代器,在迭代环境中,会自动依次返回一个键,所以完全不需要在内存中实际建立键列表

in成员关系测试,map内置函数以及其他内置工具也采用了迭代协议
upper=[line.upper() for line in open('test.py')]
map(str.upper(),open('test.py'))
'y=2\n' in open('test.py')
sorted(open('test.py'))

L=[1,2,3,4,5]
for i in range(len(L)):
L[i]+=1

并行遍历:zip和map
L1=[1,2,3,4]
L2=[5,6,7,8]
zip(L1,L2)
for (x,y) in zip(L1,L2):
print x,y,'--',x+y
当参数长度不同的时候,zip会以最短序列的长度为准来阶段所得到的元组

使用zip来构造字典
key=['spam','eggs','toast']
vals=[1,3,5]
D={}
for (k,v) in zip(key,vals):
D[k]=v

D1=dict(zip(key,vals))

产生偏移和元素:enumerate
s='spam'
for (offer,item) in enumerate(s):
print item,'appears at offset',offset

E=enumerate(s)
E.next()
E.next()

列表解析:初探
L=[x+10 for x in L]
lines=[line.rstrip() for line in lines]

扩展列表解析语法
lines=[line.rstrip() for line in open('test.py') if line[0]=='p']
res=[]
for line in open('test.py'):
if line[0]=='p':
res.append(line.rstrip())

posted on 2015-11-04 17:32  SqLer  阅读(259)  评论(0编辑  收藏  举报