Python之语句与函数

Python语句

赋值语句

>>> (x,y) = (5,10)
>>> x
5
>>> y
10
>>> x,y = 5,10
>>> x,y
(5, 10)
>>> [x,y,z] = [1,2,3]
>>> x,y,z
(1, 2, 3)
>>> x,y = y,x
>>> x,y
(2, 1)
>>> [a,b,c] = (1,2,3)
#序列赋值
>>> a,b,c = 'abc'
>>> a
'a'
>>> b
'b'
>>> c
'c'
#左右两边不一致
>>> a,b,*c = 'abcdefgh'
>>> a
'a'
>>> b
'b'
>>> c
['c', 'd', 'e', 'f', 'g', 'h']
>>> a,*b,c = 'abcdefgh'
>>> a
'a'
>>> b
['b', 'c', 'd', 'e', 'f', 'g']
>>> c
'h'

>>> s = 'abcderf'
>>> a,b,c = s[0],s[1],s[2:]
>>> a
'a'
>>> b
'b'
>>> c
'cderf

>>> a,b,c,*d = 'abc'
>>> a
'a'
>>> b
'b'
>>> c
'c'
>>> d
[]


>>> a = b = c = 'hello'
>>> a
'hello'
>>> b
'hello'
>>> a = 'hello'
>>> b = 'world'
>>> print(a,b)
hello world
>>> print(a,b,sep='|')
hello|world
>>> print(a,b,sep='|',end='...\n')
hello|world...
>>> print(a,b,end='...\n',file=open('result.txt','w'))

条件语句

score = 75
if score >= 90:
    print('优秀')
elif score >= 80:
    print('良好')
elif score >= 60:
    print('及格')
else:
    print('不及格')
def add(x):
    print(x + 10)

operation = {
    'add': add,
    'update': lambda x: print(x * 2),
    'delete': lambda x: print(x * 3)
}

operation.get('add')(10)
operation.get('update')(10)
operation.get('delete')(10)

#三元表达式
result = '及格' if score >= 60 else '不及格'

循环语句

while循环

x = 'hello world'
while x:
    print(x,end='|')
    x = x[1:]
#hello world|ello world|llo world|lo world|o world| world|world|orld|rld|ld|d|


#continue
x = 10
while x:
    x -= 1
    if(x % 2 != 0):
        continue
    print(x)
 
 #break、else
 while True:
    name = input('请输入姓名:')
    if name == 'stop':
        break
    age = input('请输入年龄:')
    print('{}---{}'.format(name,age))
else:
    print('循环结束')
    
    
#else

for循环

for x in [1,2,3,4]:
    print(x, end='|')
    

for key in emp:
    print(key)
for k,v in emp.items():
    print(k,v)
    
    
s1 = 'abcd'
s2 = 'cdef'
result = []
for x in s1:
    if x in s2:
        result.append(x)
        
result = [x for x in s1 if x in s2]

for x in range(1,100):
    print(x)
for x in range(1,101,2):
    print(x)
    

for index,item in enumerate(s1):
    print(index,item)

迭代

迭代协议:__ next__()

全局函数:next()

f = open('a.txt',encoding='utf8')
for line in f:
    print(line)

可迭代的对象分为两类:

? 迭代器对象:已经实现(文件)

? 可迭代对象:需要iter()-->__ iter__方法生成迭代器(列表)

f = open('a.txt')
iter(f) is f
True
l = [1,2,3]
iter(l) is l
False

l = iter(l)
l.__next__()
1
l = [1,2,3]
res = [x + 10 for x in l ]
res
[11, 12, 13]

res = [x for x in l if x >= 2]
res
[2, 3]
result = zip(['x','y','z'],[1,2,3])
result
<zip object at 0x0000029CBB535FC8>
for x in result:
    print(x)
    
('x', 1)
('y', 2)
('z', 3)

Python之函数

函数的作用域:

  • Local
  • Global
  • Built-in
  • Enclousure(nolocal)
x = 100
def func():
    x = 0
    print(x)
print('全局x:', x)
func()

全局x: 100
0
------------------------------------------
x = 100
def func():
    global x
    x = 0
    print(x)
print('全局x:', x)
func()
print('全局x:', x)

全局x: 100
0
全局x: 0
def func():
    x = 100
    def nested():
        x = 99
        print(x)
    nested()
    print(x)

func()

99
100
--------------------------------------------------------------
def func():
    x = 100
    def nested():
        nonlocal x
        x = 99
        print(x)
    nested()
    print(x)

func()
99
99

参数

不可变类型:传递副本给参数

可变类型:传递地址引用

def fun(x):
    x += 10
x = 100
print(x)
fun(x)
print(x)

100
100
---------------------------
def func(l):
    l[0] = 'aaa'
l = [1,2,3,4]
print(l)
func(l)
print(l)

[1, 2, 3, 4]
['aaa', 2, 3, 4]
----------------------------------------
def func(str):
    str = 'aaa'
str = '124'
print(str)
func(str)
print(str)

124
124
-------------------------------------------
def func(l):
    l[0] = 'aaa'
l = [1,2,3,4]
print(l)
func(l.copy())
print(l)

[1, 2, 3, 4]
[1, 2, 3, 4]
---------------------------------------------
def func(l):
    l[0] = 'aaa'
l = [1,2,3,4]
print(l)
func(l[:])
print(l)

[1, 2, 3, 4]
[1, 2, 3, 4]

*args和**kwargs

def avg(score, *scores):
    return score + sum(scores) / (len(scores) + 1)


print(avg(11.2,22.4,33))
scores = (11,22,3,44)
print(avg(*scores))

----------------------------------------------------------------
emp = {
    'name':'Tome',
    'age':20,
    'job':'dev'
}


def display_employee(**employee):
    print(employee)


display_employee(name='Tom',age=20)
display_employee(**emp)

lambda

f = lambda name:print(name)
f('Tom')

f2 = lambda x,y: x+y
print(f2(3,5))


f3 = lambda : print('haha')
f3()


------------------------------
def hello(action,name):
    action(name)

hello(lambda name:print('hello',name),'Tom')

--------------------------------
def add_number(x):
    return x+5


l = list((range(1,10)))
#map这种方式特别灵活,可以实现非诚复杂的逻辑
print(list(map(add_number,l)))
print(list(map(lambda x:x**2,l)))
def even_number(x):
    return x % 2 == 0


l = list(range(1,10))
print(list(filter(even_number,l)))
print(list(filter(lambda x : x % 2 == 0,l)))

相关推荐