Calculations in variables and input parameters Pro Preview

In Python, we can write mathematical equations to variables and input parameters. What happens is that the variables and parameters themselves don't store the equation, but rather calculate it and use it's result.

To access the full video please subscribe to FLLCasts.com

Subscribe

  • #1549
  • 27 Feb 2020

Basic mathematical operators in Python.

The mathematical operators in the equations that we write in Python are written using the following signs:

  • "+" addition;
  • "-" subtraction
  • "*" multiplication
  • "/" division

There are other mathematical operations we can use, but these are the fundamentals.

How to use expressions as a variable value

Let's look at an example where the speed is set using the expression 250 +250:

Motor(Port.B).run_time(250 + 250, 3000, Stop.COAST, False)
Motor(Port.C).run_time(250 + 250, 3000, Stop.COAST)

In this example, the motors are turning at a speed of 500. These expressions can be stored in a variable "motor_speed" and this variable can be replaced in the speed input parameters.

# Create your objects here. 
ev3 = EV3Brick()

speed = 250 + 250

# Write your program here.
Motor(Port.B).run_time(speed, 3000, Stop.COAST, False)
Motor(Port.C).run_time(speed, 3000, Stop.COAST)

How do expressions depend on variables

This way we can create variables that rely on other variables. Here's an example where the "motor_speed" variable is equal to the new "distance" variable divided by the new "move_time" variable:

# Create your objects here. 
ev3 = EV3Brick()

time = 3000
distance = 100
speed = distance / time

# Write your program here.
Motor(Port.B).run_time(speed, time, Stop.COAST, False)
Motor(Port.C).run_time(speed, time, Stop.COAST)

Let's look at an example where the robot needs to turn in an arch. The experiment will be run at the maximum speed of the motors and it will be changed up a lot, but we know, that the lowest speed of the slower motor will always be half of the speed of the faster motor:

# Create your objects here.
ev3 = EV3Brick()

speed = 1000

# Write your program here.
Motor(Port.B).run_time(speed, 3000, Stop.COAST, False)
Motor(Port.C).run_time(speed / 2, 3000, Stop.COAST)

Notice that only one variable is used and the input parameter of the "run_time" command on Motor C uses the speed variable divided by 2. This way we can reduce the number of variables in our program and create interconnections between the variables whenever that is required.

Courses and lessons with this Tutorial

This Tutorial is used in the following courses and lessons

Image for Python with LEGO Mindstorms EV3 - Level 1
  • 74
  • 28:18
  • 114
Image for Lesson 4 - Strange Bot
  • 7
  • 5
  • 11
  • 3d_rotation 1