python基本语句

版权声明:所有内容仅供大家学习与复习使用,请勿用于任何商业用途;维特根斯坦曾说过,凡可说的,皆无意义。凡有意义的,皆不得不以荒唐的语言传递其意义。我十分赞同。 https://blog.csdn.net/qq_40828914/article/details/86660445

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=d
	print(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+=1

	
1 2 3 4 5 6 7 8 9 10 
>>> x=9
>>> while x:
	x=x-1
	if x%2==0: continue
	print(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=k
	print(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+=1

	
j 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 += 1

	
a 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函数

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

猜你喜欢

转载自blog.csdn.net/qq_40828914/article/details/86660445
今日推荐