解压可迭代对象中的位置参数
list1 = [1, 2, 3, 4, 5]
head, *tail= list1
print("head", head)
print("tail", tail)
list1 = [1, 2, 3, 4, 5]
head, *_, tail = list1
print("head", head)
print("tail", tail)
函数形参中的位置参数
- 位置限定参数
/
,该参数之前只能通过位置传递,不能通过关键字
def greet(name, /, age):
print(f"Hello, {name}! You are {age} years old")
greet("Alice", 30)
greet("Alice", age=30)
greet(name="Alice", age=30)
- 关键字限定参数
*
,该参数之后只能通过关键字传递,不能通过位置传递
def greet(name, *, age):
print(f"Hello, {name}! You are {age} years old")
greet("Alice", 30)
greet("Alice", age=30)
greet(name="Alice", age=30)
def add(*args):
total = 0
for i in args:
total += i
return total
total = add(1, 2, 3, 4, 5)
print("total",total)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key} : {value}")
print_info(name="Alice", age=30, city="Beijing")