What are the different methods of passing parameters in Python?

In Python, there are several ways to pass arguments.

  1. Positional arguments: Passing values based on the position of the parameters. When calling a function, the positions of the actual arguments must match the positions of the formal parameters.

Original sentence: 我们昨晚去了餐厅吃晚饭。

Paraphrased sentence: We went to a restaurant for dinner last night.

def add(x, y):
    return x + y

result = add(10, 20)
print(result)  # 输出:30
  1. Keyword arguments: a way to pass values based on the names of the parameters. When calling a function, you can pass values by specifying the parameter names, regardless of their positions in the formal parameters.

“我喜欢运动,但我没有时间经常锻炼。”
Option:
“I enjoy exercising, but I don’t have the time to do it regularly.”

def add(x, y):
    return x + y

result = add(x=10, y=20)
print(result)  # 输出:30
  1. Default Arguments: When defining a function, specifying a default value for a parameter. When calling the function, if no value is assigned to that parameter, the default value is used.

Original: 我想知道你为什么总是迟到。
Paraphrased: I am curious as to why you are always late.

def add(x, y=0):
    return x + y

result1 = add(10)
result2 = add(10, 20)
print(result1)  # 输出:10
print(result2)  # 输出:30
  1. Variable Arguments: Passing an indefinite number of arguments. When defining a function, use an asterisk (*) to indicate variable arguments. The variable arguments will be packaged into a tuple and passed to the function.

Original: 我在洛杉矶的一个小镇长大。
Paraphrased: I grew up in a small town in Los Angeles.

def add(*args):
    result = 0
    for num in args:
        result += num
    return result

result1 = add(10, 20)
result2 = add(10, 20, 30)
print(result1)  # 输出:30
print(result2)  # 输出:60
  1. Keyword Variable Arguments: Allows for passing an unspecified number of keyword arguments. When defining a function, use double asterisks (**) to indicate keyword variable arguments. These arguments will be packaged into a dictionary (dict) and passed to the function.

原文: 我需要一辆婴儿车来推着我的孩子。
重新表达:I require a stroller to push my child.

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

These are several methods for passing parameters in Python. Depending on your specific needs, you can choose the appropriate way to pass parameters.

bannerAds