python函数形参用法实例分析
时间: 2024-01-13 08:13:20 浏览: 102
函数形参是函数定义中用于接收参数值的变量。通过函数形参,我们可以将外部的数据传递给函数,并在函数内部对这些数据进行处理和操作。 Python函数形参的用法可以有很多种,下面是一些实例分析:
1. 位置参数形参:
位置参数形参是最常见的形参类型,它根据参数在函数调用时的位置来确定传递给函数的值。例如:
```python
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
```
输出结果为:Hello, Alice!
2. 默认参数形参:
默认参数形参是在函数定义时给形参指定默认值,当函数调用时没有传递对应的实参时,将使用默认值。例如:
```python
def greet(name="World"):
print("Hello, " + name + "!")
greet() # 没有传递实参,使用默认值
greet("Alice") # 传递实参,使用传递的值
```
输出结果为:
Hello, World!
Hello, Alice!
3. 可变参数形参:
可变参数形参允许函数接受任意数量的实参。在函数定义时,可以使用 *args 来表示可变参数形参。例如:
```python
def sum(*args):
total = 0
for num in args:
total += num
return total
result = sum(1, 2, 3, 4)
print(result)
```
输出结果为:10
4. 关键字参数形参:
关键字参数形参允许函数接受任意数量的以关键字参数形式传递的实参。在函数定义时,可以使用 **kwargs 来表示关键字参数形参。例如:
```python
def greet(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
greet(name="Alice", age="25")
```
输出结果为:
name: Alice
age: 25
阅读全文
相关推荐















