函数
定义函数
def multiply(s, times):
return s * times
# with type annotations 类型注解
def multiply(s: str, times: int) -> str:
return s * times
# with default value for parameters
def multiply2(s: str, times: int = 2) -> str:
return s * times
想了解更多“类型注解”,查看这里: https://peps.python.org/pep-0484/
调用函数
s = multiply("literank.com", 3)
print(s) # literank.comliterank.comliterank.com
print(multiply2("literank")) # literankliterank
可变位置参数
def total(*args):
t = 0
for arg in args:
t += arg
return t
print(total(1, 2, 3)) # 6
print(total(1, 2, 3, 4, 5, 6)) # 21
可变关键字参数
def list_items(**kwargs):
for kw in kwargs:
print(kw, '->', kwargs[kw])
list_items(alice=4, bob=8, cindy=9, douglas=10) # alice -> 4, bob -> 8 ...
返回多个值
def swap(x: int, y: int) -> (int, int):
return y, x
a, b = 10, 20
c, d = swap(a, b)
print(c, d) # 20, 10
嵌套函数
def outer():
def inner():
print("inner")
print("outer begins")
inner()
print("outer ends")
outer()
匿名内联函数(即 Lambda 函数)
plus_three = lambda a: a + 3
print(plus_three(2)) # 5
# use lambda function as a argument
l = [(1, 2), [5, 1], [8,9]]
print(l) # [(1, 2), [5, 1], [8, 9]]
l.sort(key=lambda a: a[1]) # sort by the second child of the element
print(l) # [[5, 1], (1, 2), [8, 9]]
代码挑战
修改编辑器中代码,使得记录按照考试分数降序排列。
Loading...
> 此处输出代码运行结果