Python游戏世界打怪升级之新手指引十一【函数】
函数
今天,我们来学习Python的函数,再Python中,函数是组织代码的基本单元,可以用来封装可以复用的代码块。Python支持普通函数、匿名函数Lambda;并且提供了灵活的参数传递机制。下面就让我们一起来实践一下
主要有以下几个方面
-
定义函数
-
函数的调用
-
函数的参数传递
- 默认参数
- 关键字参数
- 位置参数
- 可变参数(
*args和**kwargs)
-
参数传递的注意事项
-
匿名函数Lambda
定义函数
# 函数的定义,普通函数使用 def 关键字定义,可以包含参数和返回值。
def greet(name):
return f"Hello,{name} "
调用函数
result = greet("Alice")
print(result) # Hello,Alice
函数的参数传递
默认值参数
# 默认参数,默认参数在定义函数时指定默认值,调用时可以不传递,也可以传递一个新值给到对应的变量名
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
reply = input(prompt)
if reply in {'y', 'ye', 'yes'}:
return True
if reply in {'n', 'no', 'nop', 'nope'}:
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
# 上面的函数可以用以下方式进行调用
# 只给出必选实参
ask_ok('Do you really want to quit?') # prompt = 'Do you really want to quit?'
# 给出一个可选实参
ask_ok('OK to overwrite the file?', 2)
# 给出全部的实参
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
关键字参数
# 关键字参数,关键字参数通过参数名传递,可以不按顺序。
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
# 该函数接受一个必选参数(voltage)和三个可选参数(state, action 和 type)。
# 该函数可用下列方式调用
parrot(1000) # 1 个位置参数
parrot(voltage=1000) # 1 个关键字参数
parrot(voltage=1000000, action='VOOOOOM') # 2 个关键字参数
parrot(action='VOOOOOM', voltage=1000000) # 2 个关键字参数
parrot('a million', 'bereft of life', 'jump') # 3 个位置参数
parrot('a thousand', state='pushing up the daisies') # 1 个位置参数,1 个关键字参数
# 上面调用方式可以看出来,关键字参数必须跟在位置参数后面,所有传递的关键字参数都必须匹配一个函数接收的参数
# 关键字参数的顺序不重要
位置参数
# 位置参数,位置参数是按照参数的位置顺序传递的;顺序不一样得到的结果也就不一样
def add(a, b):
return a - b
result = add(3, 5) # 3 赋值给 a,5 赋值给 b
print(result) # 输出: -2
result = add(5, 3) # 3 赋值给 a,5 赋值给 b
print(result) # 输出: 2
可变参数(*args 和 **kwargs)
# *args 形参接收一个元组,该元组包含形参列表之外的位置参数
# 最后一个形参为 **kwargs 形式时,接收一个字典
# *args:接收任意数量的位置参数
# *args 将参数打包成一个元组。
def sum_all(*args):
return sum(args)
result = sum_all(1, 2, 3, 4)
print(result) # 输出: 10
# **kwargs:接收任意数量的关键字参数
# **kwargs 将参数打包成一个字典
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
"""
输出
name: Alice
age: 25
city: New York
"""
# `*args` 和 `**kwargs`一起使用
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
# 调用上面的函数
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
"""
输出,注意关键字参数再输出结果中的顺序和调用函数时候的顺序是一致的
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
"""
函数注解
# 函数的注解,是可选的,用户自定义函数类型的元数据完整信息
# 下面的示例有一个必须的参数、一个可选的关键字参数以及返回值都带有相应的标注:
def f(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:", f.__annotations__)
print("Arguments:", ham, eggs)
return ham + ' and ' + eggs
f1 = f('spam')
print(f1)
"""
Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
Arguments: spam eggs
spam and eggs
"""
参数传递的注意事项
# 不可变对象(如整数、字符串、元组),传递的是值的副本,函数内修改不会影响原始值
def modify(x):
x = 10
a = 5
modify(a)
print(a) # 5
# 可变对象(如列表、字典),传递的是引用,函数内修改会影响原始值
def modify_list(lst):
lst.append(2)
my_list = [1,3,4]
modify_list(my_list)
print(my_list) # [1, 3, 4, 2]
匿名函数
# 匿名函数Lambda
# 匿名函数是一种简洁的定义方式,一般用于简单操作,不需要定义函数名
# 语法:lambda 参数:表达式
square = lambda x : x** 2
print(square(3)) # 9
def make_incrementor(n):
return lambda x: n + x
f = make_incrementor(42)
print(f(0)) # 42
print(f(1)) # 43
print(f(2)) # 44
print(f(3)) # 45
# lambda函数常用于需要简单函数的场景,例如排序、过滤等
# 排序
# 按元组的第二个元素排序
pairs = [(1,2),(4,1),(3,5)]
pairs.sort(key=lambda x:x[1])
print(pairs) # [(4, 1), (1, 2), (3, 5)]
# 过滤
# 过滤偶数
numbers = [1,2,3,4,5,6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6]

浙公网安备 33010602011771号