Basic mathematical operators in Python
The math operators in equations that we can write in python are written using the following symbols:
- "+" addition;
- "-" subtraction;
- "*" multiplication;
- "/" division.
There are other math operators that we can use, but these are the essentials.
Changing a variable
Here's an example of a program, where the "speed" variable has a value of 100 on the first line and then we add 200 to it on the second line:
speed = 100
speed = speed + 200
Instead of having to calculate what the new value of the "speed" variable would be and set it to be equal to 300, here we have written that we want it to be equal to itself plus 200.
Here's what an example program looks like, where a motor is moving with a speed of 100 for one second and then move with a speed of 300 for one more second:
# Create your objects here.
ev3 = EV3Brick()
motor = Motor(Port.D)
# Write your program here.
ev3.speaker.beep()
speed = 100
motor.run(speed)
wait(1000)
speed = speed + 200
motor.run(speed)
wait(1000)
Shortened syntax
The addition demonstrated in the examples above "speed = speed + 100" can be written as follows:
speed += 100
When we write a math operation right before the "=" character, Python executes this mathematical operation using the variable, whose value we want to change. The same can be applied with any math operator:
speed += 100
speed /= 100
speed *= 100
speed -= 100