def <name>(arg0, arg1, ... argN):
# TODO
def add(a, b):
return a + b
def main():
sum = add(1, 2)
print(sum)
if __name__ == "__main__":
main()
# 输出:
# 3
f = [lambda x: x**2, lambda x: x**3]
def main():
a = f[0](2)
b = f[-1](2)
print(a)
print(b)
if __name__ == "__main__":
main()
# 输出:
# 4
# 8
def add(a, b):
return a + b
def my_print(a):
print(a)
def main():
sum = add(1, 2)
pt = my_print(1)
print(sum)
print(pt)
if __name__ == "__main__":
main()
# 输出:
# 1
# 3
# None
def gen(N):
for i in range(N):
yield i ** 2
def main():
for i in gen(5):
print(i)
if __name__ == '__main__':
main()
'''
输出:
0
1
4
9
16
'''
var = 1
def f():
global var
var = 100
def main():
f()
print(var)
if __name__ == "__main__":
main()
# 输出:
# 100
var = 1
def f():
# global var
var = 100
def main():
f()
print(var)
if __name__ == "__main__":
main()
# 输出:
# 1
def f():
var = 1
def g():
nonlocal var
print(var)
var += 1
return g
def main():
g = f()
g()
g()
g()
if __name__ == "__main__":
main()
# 输出:
# 1
# 2
# 3
def f():
var = 1
def g():
# nonlocal var
print(var)
var += 1
return g
def main():
g = f()
g()
g()
g()
if __name__ == "__main__":
main()
# 输出:
# UnboundLocalError: local variable 'var' referenced before assignment
def f(a):
if isinstance(a, list):
for i in range(len(a)):
if isinstance(a[i], int) or isinstance(a[i], float):
a[i] += 1
def main():
a = [1, 2, 3]
f(a)
print(a)
if __name__ == "__main__":
main()
# 输出:
# [2, 3, 4]
def times(x, y):
return x * y
def main():
a = times(2, 4)
b = times("hello ", 3)
print(a)
print(b)
if __name__ == "__main__":
main()
# 输出:
# 8
# hello hello hello
def f(a, b):
a = 100
b[0] = "hello"
def main():
a = 1
b = [1, 2, 3]
f(a, b)
print(a)
print(b)
if __name__ == "__main__":
main()
# 输出:
# 1
# ['hello', 2, 3]
语法 | 使用时期 | 解释 |
---|---|---|
func(value) | 函数调用 | 常规参数:通过关键字进行匹配 |
funv(name=value) | 函数调用 | 关键字参数:通过变量名匹配 |
func(*sequence) | 函数调用 | 以name传递所有对象,并作为独立的基于位置的参数 |
func(**dict) | 函数调用 | 以name成对地传递所有的关键字/值,并作为独立的关键字参数 |
def func(name) | 函数定义 | 常规参数:通过位置/变量名进行匹配 |
def func(name=value) | 函数定义 | 默认参数值,如果没有在调用中传递的话 |
def func(*name) | 函数定义 | 匹配并收集(在元祖中)所有包含位置的参数 |
def func(**name) | 函数定义 | 匹配并收集(在字典中)所有包含位置的参数 |
def func(*args, name) | 函数定义 | 参数必须在调用中按照关键字传递 |
def func(*, name=value) | 函数定义 | Python 3.0及之后版本的规则,同上 |
在函数定义中,参数的出现顺序:
任何一般参数name -> 任何默认参数name=value -> *name(Python 3.0及之后版本可以用*) -> name/name=value(Python 3.0及之后版本中的key-only参数)。-> **name。
在函数调用中,参数的出现顺序:
任何位置参数value -> 任何关键字参数name=value和*sequence形式的组合 -> **dict参数。
def f(a, b, c):
print(a, b, c)
def main():
f(1, 2, 3)
# f(1) # TypeError: f() missing 2 required positional arguments: 'b' and 'c'
if __name__ == "__main__":
main()
# 输出:
1, 2, 3
def f(a, b=3, c=5):
print(a, b, c)
def main():
f(1, 2, 3)
f(10)
f(100, b=1)
f(1000, c=2)
f(10000, c=1, b=2)
f(c=1, a=100000, b=2)
f(c=1, b=2, 1000000) # SyntaxError: positional argument follows keyword argument
if __name__ == "__main__":
main()
'''
输出:
1 2 3
10 3 5
100 1 5
1000 3 2
10000 2 1
100000 2 1
'''
def f(a, b=3, c=5):
print(a, b, c)
def main():
f(1)
if __name__ == "__main__":
main()
# 输出:
# 1, 3, 5
def f(a=3, b, c=5):
print(a, b, c)
def main():
f(1)
if __name__ == "__main__":
main()
# 输出:
# SyntaxError: non-default argument follows default argument
def f(a, *pargs, **kargs):
print(a, pargs, kargs)
def main():
f(1, 2, 3, 4, x=5, y=6)
if __name__ == "__main__":
main()
# 输出:
# 1 (2, 3, 4) {'x': 5, 'y': 6}
# 元组的解包
def f(*a): # 接收序列参数
print(a) # 直接打印序列参数
print(*a) # 解包元祖
def g(a, b, c, d):
print(a, b, c, d)
def main():
t = (1, 2, 3, 4)
f(*t)
g(*t)
if __name__ == "__main__":
main()
# 字典的解包
def f(**a): # 接收字典参数
print(a) # 直接打印字典参数
print(*a) # 注意,这里是得到字典键
# print(**a) # TypeError: 'a' is an invalid keyword argument for print()
def g(a, b, c):
print(a, b, c)
def main():
d = {
'a': 1, 'b': 2, 'c': 3}
f(**d)
g(**d)
if __name__ == "__main__":
main()
def f(a, b=2, *c, d=4, **e):
print('a: ', a)
print('b: ', b)
print('c: ', c)
print('d: ', d)
print('e: ', e)
def main():
f(1, 10, 3, 4, 5, 6, 7)
print('------------------------------')
f(1, d=100, *(3, 4, 5, 6, 7))
print('------------------------------')
f(1, c=(3, 4, 5, 6, 7), d=1000)
print('------------------------------')
f(1, *(3, 4, 5, 6, 7), d=10000)
print('------------------------------')
f(1, 3, (4, 5, 6, 7), **dict(d=100000, e=8, f=9))
print('------------------------------')
f(1, 3, (4, 5, 6, 7), **dict(e=8, f=9))
print('------------------------------')
f(1, 3, (4, 5, 6, 7), e=8, f=9, d=4)
if __name__ == "__main__":
main()
'''输出
a: 1
b: 10
c: (3, 4, 5, 6, 7)
d: 4
e: {}
------------------------------
a: 1
b: 3
c: (4, 5, 6, 7)
d: 100
e: {}
------------------------------
a: 1
b: 2
c: ()
d: 1000
e: {'c': (3, 4, 5, 6, 7)}
------------------------------
a: 1
b: 3
c: (4, 5, 6, 7)
d: 10000
e: {}
------------------------------
a: 1
b: 3
c: ((4, 5, 6, 7),)
d: 100000
e: {'e': 8, 'f': 9}
------------------------------
a: 1
b: 3
c: ((4, 5, 6, 7),)
d: 4
e: {'e': 8, 'f': 9}
------------------------------
a: 1
b: 3
c: ((4, 5, 6, 7),)
d: 4
e: {'e': 8, 'f': 9}
'''
def add(*a):
return sum(*a)
def f(func, *a):
return func(a)
def main():
sum = f(add, 1, 2, 3, 4)
print(sum)
if __name__ == "__main__":
main()
# 输出:
# 10
def f(a, b):
return a + b
def main():
f.__handles__ = "F_Handle" # 增加自定义属性
print(dir(f))
print(dir(f.__call__))
print(dir(f.__class__))
print(dir(f.__code__))
if __name__ == "__main__":
main()
'''
输出:
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__handles__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__objclass__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_posonlyargcount', 'co_stacksize', 'co_varnames', 'replace']
'''
def f(a: 'float', b: 'float') -> float:
return a + b
def main():
print(f.__annotations__)
if __name__ == "__main__":
main()
# 输出:{'a': 'float', 'b': 'float', 'return': }
def main():
f = lambda x, y: x + y
print(f(1, 2))
if __name__ == "__main__":
main()
# 输出:3
def main():
f = (lambda x: (lambda y: x + y))
g = f(1)
print(g(2))
if __name__ == "__main__":
main()
# 输出:3
def f(x):
return x ** 2
def main():
o = map(f, [1, 2, 3, 4])
print(o)
print(list(o))
if __name__ == "__main__":
main()
# 输出:
#
# [1, 4, 9, 16]
def main():
l = list(map(lambda x: x ** 2, [1, 2, 3, 4]))
print(l)
if __name__ == "__main__":
main()
# 输出:
# [1, 4, 9, 16]
def main():
l = list(filter(lambda x: x > 0, range(-5, 5)))
print(l)
if __name__ == "__main__":
main()
# 输出:
# [1, 2, 3, 4]
from functools import reduce
def main():
sum = reduce((lambda x, y: x + y), [1, 2, 3, 4])
print(sum)
if __name__ == "__main__":
main()
x = [1, 2, 3, 4]
def f():
x.append(5)
def main():
f()
print(x)
if __name__ == "__main__":
main()
# 输出:[1, 2, 3, 4, 5]
x = [1, 2, 3, 4]
def f():
x = 2
return x
def main():
x = f()
print(x)
if __name__ == "__main__":
main()
# 输出:2
变量名解析原则:L(本地作用域) -> E(上一层结构中def或lamda的本地作用域) -> G(全局作用域) -> B(内置作用域)
x = 1
y = 2
def f():
global x, z
x = 2
z = 3
return x, y
def g():
global z
return z
def main():
x, y = f()
z = g()
print(x)
print(y)
print(z)
if __name__ == "__main__":
main()
'''
输出:
2
2
3
'''
def f(x):
a = x
def g():
nonlocal a
a += 1
return a
return g
def main():
a = f(1)()
print(a)
if __name__ == "__main__":
main()
# 输出:2
def f(x):
a = x
def g():
a = 100
return a
return g
def main():
a = f(1)()
print(a)
if __name__ == "__main__":
main()
# 输出:100
以上,欢迎各位读者朋友提出意见或建议。
经过Python基础与拾遗部分的9讲,相信各位读者朋友对于Python语言已经有了初步的体会,能够进行初级的Python编程。这也是笔者对技术总结与复盘的过程,很高兴与各位读者朋友一起成长,享受进步的喜悦。
呈上Python基础与拾遗前8讲链接:
Python基础与拾遗1:Python中的数字
Python基础与拾遗2:Python中的字符串与字符串格式化
Python基础与拾遗3:Python中的列表
Python基础与拾遗4:Python中的字典
Python基础与拾遗5:Python中的元组
Python基础与拾遗6:Python中的文件
Python基础与拾遗7:Python中的数据类型总结
Python基础与拾遗8:Python中的迭代器与解析
欢迎阅读笔者后续博客,各位读者朋友的支持与鼓励是我最大的动力!
written by jiong
无人相
无我相
无众生相
无寿者相