python 传参数
时间: 2023-10-29 10:54:06 浏览: 51
在 Python 中,你可以使用函数的参数来向函数传递数据。Python 中的函数参数有以下几种类型:
1. 位置参数(Positional Arguments):按照定义时的顺序传递给函数的参数。例如:
```python
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", 25) # 输出:Hello, Alice! You are 25 years old.
```
在这个例子中,`name` 和 `age` 是位置参数。
2. 关键字参数(Keyword Arguments):通过参数名来传递给函数的参数。例如:
```python
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet(age=25, name="Alice") # 输出:Hello, Alice! You are 25 years old.
```
在这个例子中,`name` 和 `age` 是关键字参数。
3. 默认参数(Default Arguments):在函数定义时为参数指定默认值,如果在调用函数时未传递该参数,则使用默认值。例如:
```python
def greet(name, age=18):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice") # 输出:Hello, Alice! You are 18 years old.
greet("Bob", 20) # 输出:Hello, Bob! You are 20 years old.
```
在这个例子中,`age` 是默认参数,默认值为 18。
4. 可变长度参数(Variable-length Arguments):允许函数接受任意数量的参数。有两种类型:`*args` 和 `**kwargs`。例如:
```python
def greet(*names):
for name in names:
print(f"Hello, {name}!")
greet("Alice", "Bob", "Charlie") # 输出:Hello, Alice! Hello, Bob! Hello, Charlie!
```
在这个例子中,`*names` 表示接受任意数量的位置参数。
你可以根据具体的需求来选择使用哪种参数类型或它们的组合。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)