How to write a variable name
A good variable name usually has two or more words so it clearly shows what the variable stores and why it is used.
In Python, we separate words with an underscore (_) to make names easier to read. The underscore works like a space.
This naming style is called snake_case, because the words look like they are connected in a line, like a snake.
Example:
Let’s look at an example of creating variables with names like "motor_speed" and "motor_time":
motor_speed = 1000
motor_time = 2000
Where variables are created
Global variables are created after importing the libraries and before defining functions such as main(). The only code that comes before the variables is the import of the libraries used in the program.
How to use variables
When we assign a numeric value to a variable, we can use its name instead of writing the number directly.
Example:
Let’s look at an example where we create and use the variables "motor_speed" and "motor_time" to control the speed and duration of the motors’ movement:
from hub import port
import runloop
import motor_pair
motor_speed = 1000
motor_time = 2000
async def main():
# Pair motors on port B and E
motor_pair.pair(motor_pair.PAIR_1, port.B, port.E)
# Move using the variables
await motor_pair.move_for_time(motor_pair.PAIR_1, motor_time, 0, velocity=motor_speed)
runloop.run(main())