
Use functions to put chunks of code into a code block that can
be called from other places in your script. To rewrite the previous
example with functions, do the following (when you go to run this
sketch, save it as
CountEvens.py
):
# Declare global variables
n=0
# Setup function
def setup():
global n
n = 100
def loop():
global n
n = n + 1
if ((n % 2) == 0):
print(n)
# Main
setup()
while True:
loop()
In this example, the output will be every even number from 102 on.
Here’s how it works:
First, the variable n is defined as a global variable that can be
used in any block in the script.
Here, the setup() function is defined (but not ...