How to save objects in variables in Python Pro Preview

If you have a very long program, where you have programed the left motor to execute over 100 different actions, how would you change that program if you were to change the motor port? Would you traverse the code and change the port on each of those 100 lines?

To evade such a situation, variables have the ability to store objects. Here's how this helps you:

To access the full video please subscribe to FLLCasts.com

Subscribe

  • #1548
  • 11 Mar 2020

An example of an object is the motor you are using. Let's look at how a program that moves both motors would look if we extracted the ports into variables named "left_motor" and "right_motor":

# Create your objects here. 
ev3 = EV3Brick()

left_motor = Motor(Port.B) 
right_motor = Motor(Port.C)

# Write your program here. 
left_motor.run_time(500, 3000, Stop.COAST, False) 
right_motor.run_time(500, 3000, Stop.COAST)

Notice that the "run_time" commands can be called from the "left_motor" and "right_motor" variables. Now if we wish to change the actual port of the left motor, all we have to do is change the variable at the beginning of our program:

# Create your objects here.
ev3 = EV3Brick()

​​​​​​​left_motor = Motor(Port.D)
right_motor = Motor(Port.C)

# Write your program here. ​​​​​​​ 
left_motor.run_time(500, 3000, Stop.COAST, False)
right_motor.run_time(500, 3000, Stop.COAST)

Other examples of objects can be the sensors you use or devices such as the microphone in the LEGO controler

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