python学习笔记1语句

本文详细介绍了Python中的语句,包括赋值语句的多种形式,如基本赋值、元组赋值、列表赋值、顺序赋值和多目标赋值;控制语句如if、while及其逻辑运算符的使用;还有for循环和while循环的使用,包括其else子句,以及迭代器和字典迭代的应用。示例代码帮助理解各个概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解释器按行来判断语句的结束
#但如果一行多个语句就需要分号
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值