SunFounder Thales Kit for Raspberry Pi Pico, Release 1.0
Default Arguments
In MicroPython, we can use the assignment operator (=) to provide a default value for the parameter.
If we call the function without argument, it uses the default value.
def
welcome
(name, msg
=
"Welcome to China!"
):
"""This is a welcome function for
the person with the provided message"""
(
"Hello"
, name
+
', '
+
msg)
welcome(
"Lily"
)
>>> %Run -c $EDITOR_CONTENT
Hello Lily, Welcome to China!
In this function, the parameter
name
has no default value and is required (mandatory) during the call.
On the other hand, the default value of the parameter
msg
is “Welcome to China!”. Therefore, it is optional during the
call. If a value is provided, it will overwrite the default value.
Any number of arguments in the function can have a default value. However, once there is a default argument, all
arguments on its right must also have default values.
This means that non-default arguments cannot follow default arguments.
For example, if we define the above function header as:
def
welcome
(name
=
"Lily"
, msg):
We will receive the following error message:
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SyntaxError: non-default argument follows default argument
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.
124
Chapter 3. For MicroPython User
Summary of Contents for Thales Kit
Page 1: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 Jimmy SunFounder Jun 04 2021 ...
Page 2: ......
Page 4: ...ii ...
Page 6: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 2 CONTENTS ...
Page 140: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 136 Chapter 3 For MicroPython User ...
Page 164: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 160 Chapter 4 For Arduino User ...