解释器按行来判断语句的结束
#但如果一行多个语句就需要分号
a=1;b=2;print a;#结果1
#赋值语句
#前面是基本赋值,后面是元组赋值,tuple assignment
a,b='a','b'
print a
print b
print a,b#这里输出的是 a b 而不是 a,b
#列表赋值
[a,b]=[1,2]
print a#输出1
print b#输出2
#顺序赋值
a,b,c,d='HTML'
print a,b,c,d
print b,c,d,a
#多目标赋值 multiple target
a=b=c=d='菜鸟'
print a,b,c,d
#使用元组赋值
L=[1,2,3,4]
while L: #终于明白了[0:5]他的意思是从0到4 一共5个数,[1:]的意思是从第一个数到最后
front,L=L[0],L[1:] #循环式从第一个开始,把第一个数赋给front,后面的赋给L。然后第二个开始的时候,L
#[1:]就代表从第三个数
print front,L
#没有++
#重定向输出流 将输出绑定到一个文件上 下面这一段验证有问题
from sys import stdout
temp=stdout #for later use
outputfile=('D:\Program Files\Python\mashijia.dat','a')
stdout = outputfile
stdout.write('just a test')
#回复输出流
stdout = temp #重新存储
print >>outputfile,'changed for a little while\n'
from sys import stderr
print >> stderr,'error!\n'
#if和while控制语句 if elif else
#if和while不需要使用小括号括起来 但是控制语句最后需要添加一个冒号:
x=100
if x>50:
print 'x is high'
elif x==50:
print 'x is middle'
else :
print 'x is low'
#逻辑运算符 与或非
y=0
if x:
print 'x is true'
if x and y:
print 'x and y are all true'
else:
print 'there is a bad guy!'
#三元运算符
#在c语言中是A=X?Y:Z 而在python中式A =Y if X else Z
#while语句 同c一样,他里面也有break和continue ,并且还添加了else功能,
x=5
L=[2,4]#又明白一点 这里不能写成Python ,用python后面只能是字符串 然元组只能用单个字符赋值
#例如python=2 后面在写成python*2 这是错的
while x:
print 2*x
x-=1
else:
print 'finished!'
#for循环控制语句
#一个列表来确定for循环的范围
x=[1,2,3,4]
for i in x:
print i
else:
print 'finished'
#循环一个字符串
x='python'
for i in x
print i
#元组的for循环
x=[('XHTML','CSS'),('JavaScript','Python')]
for(a,b) in x:
print (a,b)
c=a #完成了一个交换
a=b
b=c
print(a,b)
#迭代器 (iterator) 读取文件的最佳实践 best loop form
for line in open('D:\Program Files\Python\mashijia.txt'):
print line.upper()
#dictionary 字典迭代器
testDict={'name':'Chen Zhe','gender':'nas'}
for key in testDict:
print key + ':'+testDict[key]
testlist=[line for line in open('D:\Program Files\Python\mashijia.txt')]
print testlist