A function definition may contain multiple formal parameters, so a function call may also contain multiple actual parameters. There are many ways to pass actual parameters to a function, and positional parameters can be used. Positional arguments, which require the actual arguments to be in the same order as the formal parameters; keyword arguments, where each argument consists of a variable name and a value; lists and dictionaries. These methods are introduced in turn below.
1. Positional parameters
When calling a function, Python must associate each actual parameter in the function call to a formal parameter in the function definition. The simplest way to do this is based on the order of the arguments. This association is called a positional argument. To understand how this works, let's look at a function that displays pet information. This function indicates which animal a pet belongs to and what its name is, as follows:
The definition of this function indicates that it requires an animal type and a name. When calling describe_pet(), you need to provide an animal type and a name in order. For example, in the previous function call, the argument 'hamster' is stored in the formal parameter animal_type, and the argument 'harry' is stored in the formal parameter pet_name. In the function body, these two formal parameters are used to display pet information; the output describes a hamster named Harry:
2. Keywords Actual parameters
Keyword Actual parameters are name-value pairs passed to the function. You're associating the name and value directly in the argument, so there's no confusion when passing the argument to the function (you won't end up with Harry named Hamster). Keyword arguments eliminate the need to worry about the order of arguments in a function call and clearly indicate the purpose of each value in the function call.
3. Default value
When writing a function, you can specify a default value for each formal parameter
Related learning recommendations: python tutorial
The above is the detailed content of How to pass parameters in python. For more information, please follow other related articles on the PHP Chinese website!