Hướng dẫn optional arguments python
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Defining Python Functions With Optional Arguments Show
Defining your own functions is an essential skill for writing clean and effective code. In this tutorial, you’ll explore the techniques you have available for defining Python functions that take optional arguments. When you master Python optional arguments, you’ll be able to define functions that are more powerful and more flexible. In this tutorial, you’ll learn:
To get the most out of this tutorial, you’ll need some familiarity with defining functions with required arguments. Creating Functions in Python for Reusing CodeYou can think of a function as a mini-program that runs within another program or within another function. The main program calls the mini-program and sends information that the mini-program will need as it runs. When the function completes all of its actions, it may send some data back to the main program that has called it. The primary purpose of a function is to allow you to reuse the code within it whenever you need it, using different inputs if required. When you use functions, you are extending your Python vocabulary. This lets you express the solution to your problem in a clearer and more succinct way. In Python, by convention, you should name a function using lowercase letters with words separated by an underscore, such as Defining Functions With No Input ParametersIn this tutorial, you’ll use the example of a basic program that creates and maintains a shopping list and prints it out when you’re ready to go to the supermarket. Start by creating a shopping list:
You’re using a dictionary to store the item name as the key and the quantity you need to buy of each item as the value. You can define a function to display the shopping list:
When you run this script, you’ll get a printout of the shopping list:
The function you’ve defined has no input parameters as the parentheses in the function signature are empty. The signature is the first line in the function definition: You don’t need any input parameters in this example since the dictionary Using global variables in this way is not a good practice. It can lead to several functions making changes to the same data structure, which can lead to bugs that are hard to find. You’ll see how to improve on this later on in this tutorial when you’ll pass the dictionary to the function as an argument. In the next section, you’ll define a function that has input parameters. Defining Functions With Required Input ArgumentsInstead of writing the shopping list directly in the code, you can now initialize an empty dictionary and write a function that allows you to add items to the shopping list:
The function iterates through the
dictionary’s keys, and if the key exists, the quantity is increased. If the item is not one of the keys, the key is created and a value of
You’ve included two parameters in the function signature:
Parameters don’t have any values yet. The parameter names are used in the code within the function definition. When you call the function, you pass arguments within the parentheses, one for each parameter. An argument is a value you pass to the function. The distinction between parameters and arguments can often be overlooked. It’s a subtle but important difference. You may sometimes find parameters referred to as formal parameters and arguments as actual parameters. The arguments you
input when calling
The traceback will give a
You’ll look at more error messages related to using the wrong number of arguments, or using them in the wrong order, in a later section of this tutorial. Using Python Optional Arguments With Default ValuesIn this section, you’ll learn how to define a function that takes an optional argument. Functions with optional arguments offer more flexibility in how you can use them. You can call the function with or without the argument, and if there is no argument in the function call, then a default value is used. Default Values Assigned to Input ParametersYou can modify the function
In the function signature, you’ve
added the default value Parameters with default values can’t be followed by regular parameters. You’ll read more about the order in which you can define parameters later in this tutorial. The function
You can also pass required and optional arguments into a function as keyword arguments. Keyword arguments can also be referred to as named arguments:
You can now revisit the first function you defined in this tutorial and refactor it so that it also accepts a default argument:
Now when you use You should avoid using flags in cases where the value of the flag alters the function’s behavior significantly. A function should only be responsible for one thing. If you want a flag to push the function into an alternative path, you may consider writing a separate function instead. Common Default Argument ValuesIn the examples you worked on above, you used the integer The integers However, if you had a habit of buying two of everything you purchase when you go to the supermarket, then setting the default value to When the input parameter needs to be a string, a common default value to use is the empty string (
You have modified the function so that both parameters have a default value and therefore the function can be called with no input parameters: This line of code will add an item to the
In this version, if no item is passed to the function, the function sets the quantity to Therefore, you can use the variable directly within an Another common value that’s often used as
a default value is Data Types That Shouldn’t Be Used as Default ArgumentsYou’ve used integers and strings as default values in the examples above, and In this section, you’ll see why mutable data types should not be used as default values in function definitions. A mutable object is one whose values can be changed, such as a list or a dictionary. You can find out more about mutable and immutable data types in Immutability in Python and in Python’s official documentation. You can add the dictionary containing the item names and quantities as an input parameter to the function you defined earlier. You can start by making all arguments required ones:
You can now pass You’ve also added the To call the function, you’ll need to assign the data returned by the function to a variable:
You can also add a
You can see the output of this code below. The list of items to buy from the hardware store is shown first. The second part of the output shows the items needed from the supermarket:
You’ll now add a default value for the parameter
When you run this script, you’ll get the output below showing the items needed from the clothes shop, which may give the impression that this code works as intended:
However, this code has a serious flaw that can lead to unexpected and wrong results. You can add a new shopping list for items needed from the electronics store by using
You’ll see the problem when you look at the output from this code:
Both shopping lists are identical even though you assigned the output from You assigned an empty dictionary as the default value for the parameter When you call the function the second time and the default value for This behavior doesn’t happen with
immutable data types. The solution to this problem is to use another default value, such as
You can check whether a dictionary has been passed as an argument using the Now when you run your script again, you’ll get the correct output since a new dictionary is created each time you use the function with the default value for
You should always avoid using a mutable data type as a default value when defining a function with optional parameters. Using args and kwargsThere are two other types of Python optional arguments you’ll need to know about. In the earlier sections of this tutorial, you’ve learned how to create a function with an optional argument. If you need more optional arguments, you can create more parameters with default values when defining the function. However, it is possible to define a function that accepts any number of optional arguments. You can even define functions that accept any number of keyword arguments. Keyword arguments are arguments that have a keyword and a value associated with them, as you’ll learn in the coming sections. To define functions with a variable number of input arguments and keywords, you’ll need to learn about Functions Accepting Any Number of ArgumentsBefore defining a function that accepts any number of arguments, you’ll need to be familiar with the unpacking operator. You can start with a list such as the following one: >>>
The variable >>>
>>>
This time, >>>
When the asterisk or star symbol ( You may have noticed that You’re now ready to define your own functions that accept a variable number of input arguments. For the time being, you can simplify The function signature that includes
the variable number of input arguments using
You’ll often see function signatures that use the name
The first argument when calling
You can understand what’s happening with the >>>
When you display the data type, you can see that This is not
the same as passing a tuple as an argument in the function call. Using If you don’t add any additional arguments when you call the function, then the tuple will be empty: >>>
When you add Functions Accepting Any Number of Keyword ArgumentsWhen you define a function with parameters, you have a choice of calling the function using either non-keyword arguments or keyword arguments: >>>
In the first function call, the arguments are passed by position, whereas in the second one they’re passed by keyword. If you use keyword arguments, you no longer need to input arguments in the order they are defined: >>>
You can change this default behavior by declaring positional-only arguments or keyword-only arguments. When defining a function, you can include any number of optional keyword arguments to be included using
The parameter name The parameter name
The output from this code
displays the items in the dictionary
Earlier, you learned that >>>
To learn more about ConclusionDefining your own function to create a self-contained subroutine is one of the key building blocks when writing code. The most useful and powerful functions are those that perform one clear task and that you can use in a flexible manner. Using optional arguments is a key technique to achieve this. In this tutorial, you’ve learned:
A good understanding of optional arguments will also help you use functions in the standard library and in other third-party modules. Displaying the documentation for these functions will show you the function signature from which you’ll be able to identify which arguments are required, which ones are optional, and which ones are However, the main skill you’ve learned in this tutorial is to define your own functions. You can now start writing functions with required and optional parameters and with a variable number of non-keyword and keyword arguments. Mastering these skills will help you take your Python coding to the next level. Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Defining Python Functions With Optional Arguments |