SunFounder ESP32 Starter Kit
Create a Function
def function_nameparameters)
"""docstring"""
statement(s)
• A function is defined using the def keyword
• A function name to uniquely identify the function. Function naming is the same as variable naming, and both
follow the following rules.
– Can only contain numbers, letters, and underscores.
– The first character must be a letter or underscore.
– Case sensitive.
• Parameters (arguments) through which we pass values to a function. They are optional.
• The colon (:) marks the end of the function header.
• Optional docstring, used to describe the function of the function, we usually use triple quotes so that the docstring
can be expanded to multiple lines.
• One or more valid Micropython statements that make up the function body. Statements must have the same
indentation level (usually 4 spaces).
• Each function needs at least one statement, but if for some reason there is a function that does not contain any
statement, please put in the pass statement to avoid errors.
• An optional return statement to return a value from the function.
Calling a Function
To call a function, add parentheses after the function name.
def my_function():
print("Your first function")
my_function()
>>> %Run -c $EDITOR_CONTENT
Your first function
The return Statement
The return statement is used to exit a function and return to the place where it was called.
Syntax of return
return [expression_list]
The statement can contain an expression that is evaluated and returns a value. If there is no expression in the statement,
or the return statement itself does not exist in the function, the function will return a None object.
3.6. 1.6 (Optional) MicroPython Basic Syntax 293