Ms. Terkper's Digital Classroom

Introduction to Python: Basics #3

Introduction to Python - Basics #3

Welcome to the final part of Python Basics. In this lesson, we'll cover essential concepts to help you succeed when programming with the VEX EXP Python environment. You'll learn about importing libraries, controlling motors, handling sensors, and using loops for robot automation. Let's dive in!

1. Importing Libraries

To use VEX-specific functionality, you must import the required libraries. The vex library provides access to robot components:

                
from vex import *
                
            

2. Configuring Devices

Before controlling motors or sensors, you need to configure them in your code:

                
motor_left = Motor(Ports.PORT1, GearSetting.RATIO_18_1, False)
motor_right = Motor(Ports.PORT2, GearSetting.RATIO_18_1, True)
brain = Brain()
                
            

3. Moving Motors

To move a robot, use the spin or drive commands:

                
motor_left.spin(FORWARD, 50, PERCENT)
motor_right.spin(FORWARD, 50, PERCENT)
                
            

Explanation:

4. Using Sensors

To interact with the environment, you can use sensors like distance or color sensors:

                
distance_sensor = DistanceSensor(Ports.PORT3)
color_sensor = ColorSensor(Ports.PORT4)

if distance_sensor.get_distance(MM) < 100:
    brain.screen.print("Object detected!")

if color_sensor.get_color() == Colors.RED:
    brain.screen.print("Red object detected!")
                
            

5. Automating with Loops

Loops are essential for automating tasks. Use while or for loops for continuous or repeated actions:

                
while True:
    motor_left.spin(FORWARD, 50, PERCENT)
    motor_right.spin(FORWARD, 50, PERCENT)

    if distance_sensor.get_distance(MM) < 50:
        motor_left.stop()
        motor_right.stop()
        break
                
            

With these basics, you're ready to program your robot effectively. Try the questions below to test your knowledge!

1. Which library is essential for programming VEX EXP robots?

2. What method is used to start a motor in VEX EXP Python?

3. How can you check if a distance sensor detects an object less than 50mm away?

4. What does the following code do?

                    
while True:
    motor_left.spin(FORWARD, 50, PERCENT)
    if distance_sensor.get_distance(MM) < 30:
        motor_left.stop()
        break
                    
                

5. What is the role of the Brain object in VEX EXP Python?