文章目录

  • 1.赋值语句
    • 序列赋值语句:
    • 多目标赋值语句:
    • 增强赋值语句:
    • 表达式语句
  • 2.条件语句和循环语句
    • if语句:
    • while循环:
    • for循环:
    • range计数器
    • zip函数
    • enumerate函数

1.赋值语句

>>> a=1
>>> b=2
>>> c,d=a,b
>>> c,d
(1, 2)
>>> [c,d]=[a,b]
>>> c,d
(1, 2)
>>> [c,d]
[1, 2]
>>> a,b=b,a
>>> a,b
(2, 1)
>>> [a,b,c]=(1,2,3)
>>> a,c
(1, 3)
>>> (a,b,c)='abc'
>>> a,c
('a', 'c')
>>> string = 'abcd'
>>> a,b,c,d=string
>>> a,c
('a', 'c')
>>> a,b,c=string
Traceback (most recent call last):File "<pyshell#16>", line 1, in <module>a,b,c=string
ValueError: too many values to unpack (expected 3)
>>> a,b,c=string[0],string[1],string[2:]
>>> a,b,c
('a', 'b', 'cd')
>>> a,b=string[:2]
>>> c=string[2:]
>>> a,b,c
('a', 'b', 'cd')
>>> (a,b),c=string[:2],string[2:]
>>> a,b,c
('a', 'b', 'cd')
>>> ((a,b),c)=('ab','cd')
>>> a,b,c,d
('a', 'b', 'cd', 'd')
>>> range(3)
range(0, 3)
>>> a,b,c=range(3)
>>> a,b,c
(0, 1, 2)
>>> d=[1,2,3,4]
>>> while d:a,d=d[0],d[1:]print(a,d)1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
>>> a=[1,2,3,4]
>>> b,c,d,e=a
>>> print(b,c,d,e)
1 2 3 4
>>> c,d=a
Traceback (most recent call last):File "<pyshell#40>", line 1, in <module>c,d=a
ValueError: too many values to unpack (expected 2)
>>> c,*d=a
>>> c,d
(1, [2, 3, 4])
>>> *c,d=a
>>> c,d
([1, 2, 3], 4)
>>> b,*c,d=a
>>> b,c,d
(1, [2, 3], 4)
>>> b,c,*d=a
>>> b,c,d
(1, 2, [3, 4])
>>> a,*b='cde'
>>> a,b
('c', ['d', 'e'])
>>> s='cde'
>>> s[0],s[1:]
('c', 'de')
>>> d=[1,2,3,4]
>>> while d:a,*d=dprint(a,d)1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
>>> d
[]
>>> d=[1,2,3,4]
>>> a,b,c,*e=d
>>> print(a,b,c,d)
1 2 3 [1, 2, 3, 4]
>>> print(a,b,c,e)
1 2 3 [4]
>>> a,b,c,e,*f=d
>>> print(a,b,c,e,f)
1 2 3 4 []
>>> a,b,*c,e,f=d
>>> print(a,b,e,f,c)
1 2 3 4 []
>>> *a=d
SyntaxError: starred assignment target must be in a list or tuple
>>> *a,=d
>>> a
[1, 2, 3, 4]
>>> ,*a=d
SyntaxError: invalid syntax
>>> a=b=c='fgh'
>>> a,b,c
('fgh', 'fgh', 'fgh')
>>> a=b=1
>>> b=b+1
>>> a,b
(1, 2)
>>> a=b=1
>>> b+=1
>>> a,b
(1, 2)
>>> a=b=[]
>>> b.append(1)
>>> a,b
([1], [1])
>>> a=[]
>>> b=[]
>>> b.append(1)
>>> a,b
([], [1])
>>> w=1
>>> w+=1
>>> w
2
>>> s='aa'
>>> s+='bb'
>>> s
'aabb'
>>> p=[1,2]
>>> p=p+[3]
>>> p
[1, 2, 3]
>>> p.append(4)
>>> p
[1, 2, 3, 4]
>>> p+=[1,2]
>>> p
[1, 2, 3, 4, 1, 2]
>>> a=[1,2]
>>> a=b
>>> b=b+[3,4]
>>> a,b
([1], [1, 3, 4])
>>> a
[1]
>>> a=[1,2]
>>> b=a
>>> b=b+[3,4]
>>> a,b
([1, 2], [1, 2, 3, 4])
>>> a=[1,2]
>>> b=a
>>> b+=[3,4]
>>> a,b
([1, 2, 3, 4], [1, 2, 3, 4])
>>> a=[1,2]
>>> a.append(3)
>>> a
[1, 2, 3]
>>> a=a.append(4)
>>> a
>>> print(a)
None
>>> x='abc'
>>> y=1
>>> z=['sdf']
>>> print(x,y,z)
abc 1 ['sdf']
>>> print(x,y,z,sep='')
abc1['sdf']
>>> print(x,y,z,sep=', ')
abc, 1, ['sdf']
>>> print(x,y,z,end='')
abc 1 ['sdf']
>>> print(x,y,z,end='--=\n')
abc 1 ['sdf']--=
>>> print(x,y,z,sep='# ',end='@ ')
abc# 1# ['sdf']@
>>> print(x,y,z,end='@ ',sep='# ')
abc# 1# ['sdf']@
>>> print(x,y,z,sep=', ',file=open('ort.txt','w'))
>>> print(x,y,z)
abc 1 ['sdf']
>>> print(open('ort.txt').read())
abc, 1, ['sdf']>>> tt='%s:%-.2f,%04d'%('ww',123,11)
>>> print(tt)
ww:123.00,0011
>>> print('%s:%-.2f,%04d'%('ww',123,11))
ww:123.00,0011
>>> print('hello')
hello
>>> import sys
>>> sys.stdout.write('hello\n')
hello
6
>>> import sys
>>> temp=sys.stdout
>>> sys.stdout=open('a.txt','a')
>>> print('qwert')
>>> print(1,1,1)
>>> sys.stdout.close()
>>> sys.stdout=temp
>>> print('goback')
goback
>>> print(open('a.txt').read())
qwert
1 1 1>>> k=open('k.txt','a')
>>> print(a,b,c,file=k)
>>> print(z,x,c)
['sdf'] abc fgh

可以看出:

序列赋值语句:

1.右边可以是任何类型的序列,而且赋值语句执行时,python会建立临时元组,存储右侧变量原始值,然后赋值运算符右侧元组的值和左侧元组变量进行匹配,因此在交换两个变量时,不需要增加临时变量。

2.主体的数目和目标的项数必须一致。可以通过分片,嵌套序列,扩展序列解包,来改变左侧元素与右侧的对应关系

3.对于扩展序列解包来说:带星号的名称可能只匹配单个项,但是总会向其赋值一个列表,如果没有内容和其匹配,那么它会赋值一个空的列表。通过分片和扩展序列解包对比,可以发现,他们可以实现同样效果,只不过扩展序列解包减少很多输入,更加方便

多目标赋值语句:

1.多目标赋值:直接把右侧对象赋值给左侧所有提供的变量(多个目标)。

2.对于不可变对象来说,修改其中一个变量,不会对其他变量造成影响,因为不可变对象(比如数字)不支持在原处的修改;但是对于可变对象(列表或字典)来说,采用多变量赋值导致两个变量引用相同对象,对其中一个变量修改,也会影响另一个变量。因此为了避免,需要在单独的语句初始化可变对象。

增强赋值语句:

1.增强赋值:比如:a+=1替代a=a+1

2.增强赋值语句的原理:直接在原处执行修改运算。而普通的则是先创建一个新的对象,进行运算,然后把运算结果复制到左侧。因此使用增强赋值语句会执行的更快

3.对于合并列表这个例子来说:

①:p=p+[1,2]

②:p+=[1,2]

④:p.extend([1,2])

其中①语句的运行机制:创建一个新对象,把等式右边左侧的p复制到列表中,再把右侧[1,2]复制到列表中。

而使用②语句,python会自动调用extend方法,就相当于④语句,直接在内存块末尾添加项

由此可见:+=直接对列表进行原处修改,而+合并则是生成新的对象

因此,d.append返回值不是一个对象,如果我们输出d.append那么会显示none

4.因此由3可知:对于共享引用情况,对其中一个变量使用+=,两个变量都会变,而对其中一个变量使用+,只有这个变量会变。

表达式语句

1.具有自定义分隔符以及终止符的功能,而且如果想要显示更具体的格式,那么可以提前构造一个字符串,然后打印字符串。

2.对于输出流来说:我们可以重定向输出流,让他输出到我们指定文件之中。其中可以直接在print里面增加file项。或者是赋值sys.stdout,但是此时注意我们在完成指定输出之后还需回复到原始的输出流。

2.条件语句和循环语句

>>> x
's'
>>> if x=='s':print('ddff')
elif x=='fff':print('dsd')
else:print('sdf!!')ddff
>>> cho = 'ds'
>>> print({'dd':1,'dds':2,'ds':3}[cho])
3
>>> if cho == 'dd':print(1)
elif cho=='dds':print(2)
else : print(3)3
>>> g={'dsd':1,'sa':2,'er':3}
>>> print(g.get('sa','notin'))
2
>>> print(g.get('ddd','www'))
www
>>> cj='dd'
>>> if cj in g:print (g[cj])
else:print('www')www
>>> 1 or 2,3 or 4
(1, 3)
>>> [] or 3
3
>>> [] or {}
{}
>>> 2 and 3,3 and 2
(3, 2)
>>> []and {}
[]
>>> 3 and {}
{}
>>> a='dd'if 's' else 'ee'
>>> a
'dd'
>>> x='qwer'
>>> while x:print(x,end=' ')x=x[1:]qwer wer er r
>>> a=1;b=11
>>> while a<b:print(a,end=' ')a+=11 2 3 4 5 6 7 8 9 10
>>> x=9
>>> while x:x=x-1if x%2==0: continueprint(x,end=' ')7 5 3 1
>>> for x in ['a','b','c']:print(x,end=' ')a b c
>>> sum=0
>>> for x in [1,2,3,4]:sum+=x>>> sum
10
>>> for i in [1,2,3,4]:sum*=i>>> sum
240
>>> s='werty'
>>> t=('e','rt','ww')
>>> for x in s:print(x,end=', ')w, e, r, t, y,
>>> for x in t:print(x,end=' ')e rt ww
>>> g=[(1,2),(3,4),(5,6)]
>>> for (a,b) in g:print(a,b)1 2
3 4
5 6
>>> d={'a':1,'b':2,'c':3}
>>> for key in d:print(key,'=>',d[key])a => 1
b => 2
c => 3
>>> list (d.items())
[('a', 1), ('b', 2), ('c', 3)]
>>> for (key,value) in d.items():print(key,'=>',value)a => 1
b => 2
c => 3
>>> g
[(1, 2), (3, 4), (5, 6)]
>>> for k in g:a,b=kprint(a,b)1 2
3 4
5 6
>>> ((a,b),c)=((1,2),3)
>>> a,b,c
(1, 2, 3)
>>> for ((a,b),c) in [((1,2),3),((4,5),6)]:print(a,b,c)1 2 3
4 5 6
>>> for((a,b),c)in [([1,2],3),['xy',6]]:print(a,b,c)1 2 3
x y 6
>>> a,*b,c=(1,2,3,4)
>>> a,b,c
(1, [2, 3], 4)
>>> for(a,*b,c)in[(1,2,3,4),(5,6,7,8)]:print(a,b,c)1 [2, 3] 4
5 [6, 7] 8
>>> for k in [(1,2,3,4),(5,6,7,8)]:a,b,c=k[0],k[1:3],k[3]print(a,b,c)1 (2, 3) 4
5 (6, 7) 8
>>> items=['ss',11,(2,3),2.3]
>>> tests=[(4,5),3.2]
for i in tests:for j in items:if i==j:print (i,' found')break;else:print(i,'not found')(4, 5) not found
3.2 not found
>>> for i in tests:if i in items:print(i,'found')else :print(i,'not found')(4, 5) not found
3.2 not found
>>> a='wwe'
>>> b='rre'
>>> res=[]
>>> for x in a:if x in b:res.append(x)>>> res
['e']
>>> list (range(5)),list (range(2,5)),list(range(0,10,2))
([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])
>>> list(range(-5,5))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> list(range(5,-5,-1))
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
>>> for i in range(3):print(1,'pe')1 pe
1 pe
1 pe
>>> for i in range(3):print(i,'pe')0 pe
1 pe
2 pe
>>> x='jki'
>>> for i in x:print(i,end=' ')j k i
>>> i=0
>>> n=len(x)
>>> while(i<n):print(x[i],end=' ')i+=1j k i
>>> for i in range(n):print(x[i],end=' ')j k i
>>> for i in range(0,n,2):print(x[i],end=' ')j i
>>> for i in x[::2]:print(i,end=' ')j i
>>> l=[1,2,3,4,5]
>>> for x  in l:x+=1>>> l
[1, 2, 3, 4, 5]
>>> x
6
>>> n=len(l)
>>> for i in range(n):l[i]+=1>>> l
[2, 3, 4, 5, 6]
>>> a=[1,2,3,4]
>>> b=[5,6,7,8]
>>> zip(a,b)
<zip object at 0x000001B170A03D88>
>>> list(zip(a,b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> for (x,y) in zip(a,b):print(x,y,'--',x+y)1 5 -- 6
2 6 -- 8
3 7 -- 10
4 8 -- 12
>>> s1='asd'
>>> s2='ert33243'
>>> list(zip(s1,s2))
[('a', 'e'), ('s', 'r'), ('d', 't')]
>>> keys = ['dd','cc','bb']
>>> vals = [1,2,3]
>>> list(zip(keys,vals))
[('dd', 1), ('cc', 2), ('bb', 3)]
>>> d={}
>>> for (k,v) in zip(keys,vals):d[k]=v>>> d
{'dd': 1, 'cc': 2, 'bb': 3}
>>> d1=dict(zip(keys,vals))
>>> d1
{'dd': 1, 'cc': 2, 'bb': 3}
>>> s='asdf'
>>> num=0
>>> for i in s:print(i,'nto',num)num += 1a nto 0
s nto 1
d nto 2
f nto 3
>>> num=0
>>> for (num,i) in enumerate(s):print(i,'not',num)a not 0
s not 1
d not 2
f not 3
>>> for (num,i) in enumerate(s):print(i,'not',num)a not 0
s not 1
d not 2
f not 3

可以看出:

if语句:

1.if elif else 可以有多路分支,首行以冒号结尾,首行下一行嵌套的代码按缩进行的格式书写。在一个单独的嵌套块中,所有语句必须缩进相同距离。

2.对于字典来说,其get方法以及索引运算也可以通过if语句来实现

3.对于布尔and和or运算符来说,他们总是会返回对象:

or是短路计算,python从左至右,在其找到的第一个真值操作数的地方停止。如果左右都为假,那么返回右边那个对象。

and运算,python从左至右计算操作数,并停在第一个为假的对象上。如果都为真,那么返回右边那个对象

4.三元表达式:

if x :

a=b

else :

a=c

等价于=> a=b if x else c

while循环:

0.是一种迭代结构,用于重复执行某语句块。

1.while 测试表达式,首行以冒号结尾,首行下一行嵌套的代码按缩进行的格式书写。在一个单独的嵌套块中,所有语句必须缩进相同距离。python会一直循环,直到遇到break或者测试表达式为假

2.循环else:python特有,支持for和while循环,如果循环离开时没有遇到break语句,那么就会执行else块。

for循环:

1.属于序列迭代器,可用于遍历任何可迭代对象,如字符串,列表,元组。

2.首行由赋值目标和遍历对象组成,运行for循环时,序列对象元素赋值给目标,然后循环主体使用目标来引用序列当前元素。

3.循环目标本身可以时元组,字符,字符串。这可以根据遍历对象的类型更改。

4.for循环也可以遍历文件和字典,对于字典来说,可以使用items方法,让其返回一个元组列表,然后再进行for循环遍历

5.对于嵌套for循环来说,使用in运算符隐式的扫描列表来找到匹配,可以减少内层循环。

range计数器

1.range会产生一个整数列表,如果只有一个参数a,从零开始,一共a个数。如果两个参数,左闭右开。如果三个参数,那么第三个参数是步长

2.其实这个range就相当于c语言循环中常用的n。n=strlen(),然后i从0到n。因此,我们如果把列表当成c语言中数组,那么就可以把每次循环的赋值目标i作为下标,对列表进行修改。

zip函数

1.zip会把一个或多个序列中,在同一竖行的元素配成对,然后同一对的放到一个元组里,最后返回一个元组列表。

2.当几个序列长度不同时,zip会以最短序列长度来决定元组中的数目

3.我们也可以通过zip和for循环来构造字典

enumerate函数

它能同时记录偏移值和偏移值处的元素

python基本语句相关推荐

  1. 忘了python关键语句?这份备忘录拯救你的记忆

    忘了Python关键语句?这份备忘录拯救你的记忆 今天要介绍的 Python 3 Cheat Sheet 由法国国家科学研究中心(CNRS)的法国机械工程与信息技术实验室(LIMSI)的工程师 Lau ...

  2. 包教包会!7段代码带你玩转Python条件语句(附代码)

    来源:大数据 本文约5200字,建议阅读10分钟. 本文介绍了Python条件语句常用的7段代码. [ 导 读 ]条件语句通过一个或多个布尔表达式的执行结果(真值或假值)决定下一步的执行方向.所谓布尔 ...

  3. python入门语句_Python 快速入门笔记(5):语句

    本系列随笔是本人的学习笔记,初学阶段难免会有理解不当之处,错误之处恳请指正.转载请注明出处: https://www.cnblogs.com/itwhite/p/12297769.html. 简介 p ...

  4. python“ with”语句的用途是什么?

    今天,我第一次碰到了Python with语句. 我已经使用Python几个月了,甚至都不知道它的存在! 考虑到它的地位有些晦涩,我认为值得一问: Python with语句旨在用于什么? 你用它来做 ...

  5. python循环语句-Python-循环语句及循环控制语句

    循环语句允许我们执行一个语句或语句组多次,下面是在大多数编程语言中的循环语句的一般形式: Python 提供了 for 循环和 while 循环(在 Python 中没有 do..while 循环): ...

  6. python基本语法语句-Python基本语句

    一.Python 条件语句 Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: Python程序语言指定任何非 ...

  7. python基本语法语句-python基本语句有哪些

    Python是一种计算机程序设计语言.是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越来越多被用于独立的.大型项目的开发.下面我们就为 ...

  8. python输入语句-python输入语句

    广告关闭 2017年12月,云+社区对外发布,从最开始的技术博客到现在拥有多个社区产品.未来,我们一起乘风破浪,创造无限可能. python条件语句目录:1. 分支语句(if...else...)2. ...

  9. python条件语句-Python3 条件控制

    Python3 条件控制 Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: 代码执行过程: if 语句 ...

  10. python条件语句-Python 条件语句

    Python 条件语句 Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块.高佣联盟 www.cgewang.com 可以通过下图来简单了解条件语句的执行过 ...

最新文章

  1. 基于大数据的Uber数据实时监控(Part 2:Kafka和Spark Streaming)
  2. 未能为数据库 '*'中得对象'*'分配空间,因文件组'PRIMARY'已满
  3. CTFshow 信息收集 web6
  4. CentOS下配置HTTPS访问主机并绑定访问端口号
  5. Scala函数简化写法
  6. BP反向传播矩阵推导图示详解​
  7. 数据库-优化-MYSQL数据库设计规范
  8. mysql 索引优化 2_MySQL2索引优化
  9. python设计模式(十四):模板方法模式
  10. php 输出读取结果集,php获取数据库结果集实例详解
  11. source insight 导入JDK源码
  12. yii框架封装拼多多开放平台sdk
  13. 通用对话框Dialog
  14. Java项目:JSP会议-会议室管理系统
  15. 浙江卫视的万峰纯粹一烂人
  16. C++ 单词转换例子
  17. 秀动抢票教程,JS逆向分析与学习
  18. 单线程-多线程-高并发
  19. Excel 统计起止时间
  20. 网安学习-CTF夺旗

热门文章

  1. 怎样使用orapwd新建口令文件
  2. 《Introduction to Computing Systems: From bits and gates to C and beyond》
  3. windows下使用Caffe框架和matlab实现SRCNN官方代码的步骤
  4. pythonrequests证书_python requests证书问题解决
  5. word无法启动转换器recovr32_迅捷PDF转换器3.0.1Mod会员版
  6. 进入hbase命令_Zookeeper、Hbase安装部署
  7. 制作 mysql的rpm文件_自制mysql.rpm安装包
  8. android webservices 返回多行多列数据,NoahWeb实现表格多行多列
  9. java addcallback函数_java中怎么使用callback函数?
  10. Win11黑夜模式在哪开启 Win11黑夜模式怎么开启