EasyManua.ls Logo

SunFounder ESP32 - Page 301

Default Icon
771 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
SunFounder ESP32 Starter Kit
(continued from previous page)
File "<stdin>", line 6, in <module>
TypeError: function takes 2 positional arguments but 1 were given
welcome()No arguments
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
TypeError: function takes 2 positional arguments but 0 were given
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"""
print("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
3.6. 1.6 (Optional) MicroPython Basic Syntax 295

Table of Contents