Six parameters of Python?

insert image description here

Many people say that there are four or five types of parameters in Python. I personally think that there are six types of parameters, namely: positional arguments (Positional Arguments), default parameters (Default Arguments), keyword arguments (Keyword Arguments), Variable-length parameters (Variable-Length Arguments), mandatory keyword parameters (Keyword-Only Arguments), unpacking parameter lists (Unpacking Argument Lists), of course, if you have better insights, we can all refer to them, comment below also can. Today, from my perspective, I will take you to explore the six parameter types in Python functions to help you better understand the basics of Python programming.

What are the parameters?

In Python, functions are a mechanism for encapsulating reusable code. The parameter is a placeholder in the function definition, which is used to receive the value passed to the function from outside. Python supports various parameter types, let us understand them one by one.

Positional Arguments¶

Positional parameters are the most common type of parameter. They receive the passed values ​​sequentially in the order in which they are defined in the function. Let's look at a simple example:

def greet(name, greeting):
    return f"{greeting}, {name}!"

message = greet("Alice", "Hello")
print(message)  # 输出:Hello, Alice!

In this example, nameand greetingare positional parameters.

Default Arguments¶

Default parameters allow us to specify default values ​​for parameters at function definition time. If this parameter is not passed when calling the function, the default value will be used. See an example:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

message = greet("Bob")
print(message)  # 输出:Hello, Bob!

In this example, greetingthe parameter has a default value "Hello", so we don't need to pass it when calling the function.

Keyword Arguments¶

Keyword arguments allow us to specify the value passed using the parameter name, not necessarily in positional order. This makes function calls much cleaner and easier to understand. See an example:

def greet(name, greeting):
    return f"{greeting}, {name}!"

message = greet(greeting="Hi", name="Charlie")
print(message)  # 输出:Hi, Charlie!

By using parameter names, we can explicitly specify the value of each parameter, which improves the readability of the code.

Variable-length parameters (Variable-Length Arguments)

Sometimes, we are not sure how many arguments a function will receive. Python allows variable length arguments to handle this situation. There are two cases: args and * kwargs . args is used to pass any number of positional arguments, while * kwargs is used to pass any number of keyword arguments. Look at an example:

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

sum = add(1, 2, 3, 4, 5)
print(sum)  # 输出:15

In this example, we receive multiple positional arguments using args .

Mandatory keyword arguments (Keyword-Only Arguments)

Sometimes, we want function calls to have to use keyword arguments to pass certain parameters. This can be achieved by using * in the function definition. Look at an example:

def calculate_tax(*, income, tax_rate):
    return income * tax_rate

tax = calculate_tax(income=50000, tax_rate=0.2)
print(tax)  # 输出:10000.0

In this example, the function calculate_taxrequires that keyword arguments must be used to pass incomeand tax_rate.

Unpacking Argument Lists

Sometimes, we may already have an argument list, but want to unpack it and pass it to a function. This can be done by prefixing the parameter with *. Look at an example:

def greet(name, greeting):
    return f"{greeting}, {name}!"

params = ["Alice", "Hello"]
message = greet(*params)
print(message)  # 输出:Hello, Alice!

In this example, we paramsunpacked the list and passed it to the function.

Example analysis

Through the introduction of the above six parameter types, we can use Python functions more flexibly. According to actual needs, we can choose to use different parameter types such as positional parameters, default parameters, keyword parameters, and variable-length parameters. This helps to make the code more readable and maintainable.

Let's take a more in-depth understanding of Python's six parameter types through a comprehensive example. Let's say we want to write a function that calculates the total price of the items in the shopping cart, taking into account discounts and shipping. We can use various parameter types to achieve this functionality.

def calculate_total_price(items, discount=0, shipping_fee=0, tax_rate=0.1):
    subtotal = sum(items)
    total_discount = subtotal * discount
    total_price = subtotal - total_discount
    total_price *= (1 + tax_rate)
    total_price += shipping_fee
    return total_price

# 示例购物车商品价格列表
cart_items = [100, 50, 30, 80]

# 计算总价(不使用任何额外参数)
total1 = calculate_total_price(cart_items)
print("总价(不使用任何额外参数):", total1)

# 计算总价(使用折扣和税率参数)
total2 = calculate_total_price(cart_items, discount=0.1, tax_rate=0.15)
print("总价(使用折扣和税率参数):", total2)

# 计算总价(使用折扣、税率和运费参数)
total3 = calculate_total_price(cart_items, discount=0.2, tax_rate=0.1, shipping_fee=10)
print("总价(使用折扣、税率和运费参数):", total3)

In this example, we define a function calculate_total_pricethat takes a list of cart item prices items, and optional discount discount, shipping shipping_feeand tax tax_rateparameters. According to different parameter combinations, we can calculate the total price of the items in the shopping cart.

  1. Positional Arguments : In the function definition, itemsthe parameter is a positional parameter, which must be passed in the order in which the function is defined. In the function call, the shopping cart item price list is passed cart_items, which is the use of a positional parameter.

  2. Default parameters (Default Arguments) : In the function definition, discountthe , shipping_feeand tax_rateparameters have default values, which means that if the corresponding parameters are not provided when the function is called, the function will use the default value. In the first function call, these parameters were not provided, so they used default values.

  3. Keyword Arguments (Keyword Arguments) : In a function call, parameters can be passed by specifying their names, not necessarily in the order they are defined. In the second and third function calls, the value of each parameter is explicitly specified, for example discount=0.1, tax_rate=0.15, and shipping_fee=10. This is the use of keyword arguments.

Through these different parameter types, the function can be called according to actual needs, making the function more flexible and customizable. This parameter flexibility can be adapted to different scenarios and data without changing the function definition. Hope this helps you better understand the application of Python's six argument types.

insert image description here

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/132383649