Using Variables
Variable Naming Rules
- Must start with a letter or an underscore
- Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
-
Case sensitive (Delay is not the same as delay)
Challenge
Which Variable Names Are Legal?
- MrRoberts
- _goodbye!
- 2For1
- Mr.Tannenbaum
- X
- _wait
- _2
Python is both a Strongly Type and Dynamically Type Language
- Strong typing means that the type of a value doesn't change in unexpected ways. A string containing only digits doesn't magically become a number. Every change of type requires an explicit conversion.
- Dynamic typing means that runtime objects (values) have a type, as opposed to static typing where variables have a type.
What Does That Mean?
- Text (string): wait = "two"
- Number with a decimal point (float): wait = 2.0
- Number without a decimal point (int): wait = 2
- A Collection (list): wait = ["Two", 2.0, 2]
For example, the duty_u16 method from the PWM library only accepts a positive integer.
So?
We can use variables to make driving the robot car simpler. For example, we can create the following variables (use upper case to denote constants):
- SPEED = 32768
- DELAY = 2
- FREQUENCY = 1000
Now we can have the robot car easily move faster or further without changing the numbers in multiple places. The simple code we had last time becomes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
If we want to move further or change the speed we can simply change the value of the variables.
Challenge
Rewrite the main.py code to use variables
Make a larger square
Move at a different speed