在Python中,def
关键字用于定义一个函数。要设置函数的参数,您需要在括号内指定参数名称,如果有多个参数,则用逗号分隔它们。参数可以是必需的(位置参数)或可选的(带有默认值的参数)。
以下是一些示例:
def greet(name):
print("Hello, " + name)
greet("Alice")
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
def greet(name, greeting="Hello"):
print(greeting + ", " + name)
greet("Alice") # 输出 "Hello, Alice"
greet("Bob", "Hi") # 输出 "Hi, Bob"
*args
):def sum_numbers(*args):
return sum(args)
result = sum_numbers(1, 2, 3, 4, 5)
print(result) # 输出 15
**kwargs
):def print_personal_info(**kwargs):
for key, value in kwargs.items():
print(key + ": " + str(value))
print_personal_info(name="Alice", age=30, city="New York")
这将输出:
name: Alice
age: 30
city: New York