How to update a variable with an expression which includes it Pro Preview

You should already be acquainted with creating numeric variables, how to set their initial value, and how you can use them, but the main function of the variable is that it varies.

Here, we'll show you how you can change the value of numeric variables using two different syntaxes.

To access the full video please subscribe to


  • #1635
  • 25 Jun 2020

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.

speed = 100

speed = speed + 200

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

Courses and lessons with this Tutorial

This Tutorial is used in the following courses and lessons

Image for Python with LEGO Mindstorms EV3 - Level 2
  • 39
  • 19:58
  • 93
Image for Lesson 5 - Railroad Handcar
  • 4
  • 7
  • 3
  • 3d_rotation 1