SunFounder ESP32 Starter Kit
Keyword Arguments
When we call a function with certain values, these values will be assigned to arguments based on their position.
For example, in the above function welcome(), when we called it as welcome(“Lily”, “Welcome to China”), the value
“Lily” gets assigned to the name and similarly “Welcome to China” to parameter msg.
MicroPython allows calling functions with keyword arguments. When we call the function in this way, the order
(position) of the arguments can be changed.
# keyword arguments
welcome(name = "Lily",msg = "Welcome to China!")
# keyword arguments (out of order)
welcome(msg = "Welcome to China",name = "Lily")
#1 positional, 1 keyword argument
welcome("Lily", msg = "Welcome to China!")
As we can see, we can mix positional arguments and keyword arguments during function calls. But we must remember
that the keyword arguments must come after the positional arguments.
Having a positional argument after a keyword argument will result in an error.
For example, if the function call as follows:
welcome(name="Lily","Welcome to China!")
Will result in an error:
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
SyntaxError: non-keyword arg after keyword arg
Arbitrary Arguments
Sometimes, if you do not know the number of arguments that will be passed to the function in advance.
In the function definition, we can add an asterisk (*) before the parameter name.
def welcome(*names):
"""This function welcomes all the person
in the name tuple"""
#names is a tuple with arguments
for name in names:
print("Welcome to China!", name)
welcome("Lily","John","Wendy")
>>> %Run -c $EDITOR_CONTENT
Welcome to China! Lily
Welcome to China! John
Welcome to China! Wendy
296 Chapter 3. For MicroPython User