Variables#

Introduction#

Variables store data and allow you to reuse and manipulate it throughout your program. Python is a dynamically typed language, meaning you don’t need to declare the type of a variable explicitly. Instead, the type is automatically inferred based on the value assigned to it. For example:

angle = 90           # angle is an integer
dist = "Distance: "  # dist is a string
steps = 2.5          # steps is a float

Python is also strongly typed, which means you cannot perform operations on incompatible types without explicitly converting them. For example:

controller = 1                 # controller is an integer
modules = "3"                  # modules is a string
result = controller + modules  # Creates a TypeError

To resolve such issues, you must explicitly convert the types, if appropriate:

controller = 1                 # controller is an integer
modules = "3"                  # modules is a string

# Convert modules to an integer before adding.
result = int(modules) + controller

This API explains common variable types in Python. While not an exhaustive list, it covers the types you’re most likely to use in practice.

  • Local variables – Declared inside a function and only used within that scope; best for temporary or isolated values.

  • Global variables – Declared outside any function and used throughout the project; good for sharing data between functions.

  • Integer – Whole numbers used for counting, distances, or anything without decimals.

  • Float – Numbers with decimal points, useful for precise measurements or calculations.

  • String – Text values, used for messages, labels, or displaying readable output.

  • BooleanTrue or False values for logic and decision-making.

  • NoneType – Represents “no value yet,” often used as a placeholder.

  • Range – Automatically generates sequences of numbers, most commonly used in loops.

  • List – A changeable collection of items; good for storing groups of values like objects or sensor readings.

  • 2D List – A list of lists; ideal for representing rows, grids, or table-like data.

  • Tuple – A fixed sequence of values that can’t be changed; useful for grouped, unchanging data.

Declaring and Assigning a Variable#

To create a variable, simply assign a value to a name using the = operator:

distance = 100

When naming a variable, the following rules must be adhered to:

  • The name cannot contain special characters (e.g., an exclamation point).

  • The name cannot begin with a number.

  • The name cannot use spaces.

  • The name cannot be a reserved word in VEXcode (e.g. Drivetrain).

Local Variables#

Local variables are defined inside a function or block of code. They are only accessible within the scope of that function or block and are not visible outside of it.

def show_local():
    # This variable only exists inside this function.
    message = "I'm local!" 
    controller.screen.print(message)

show_local()

Local variables are commonly used to store temporary values that are only relevant within a specific function or part of the program.

Global Variables#

Global variables are defined outside of any function or block. They can be accessed and read anywhere in the program, including inside functions.

Note: Global variables are accessible from anywhere in the program, which can make them convenient for sharing data across functions. However, relying heavily on global variables can lead to unintended side effects, as changes to the variable in one part of the program may affect other parts unpredictably. For this reason, local variables are generally preferred when possible, as they limit a variable’s scope to the specific function where it is defined. This reduces the likelihood of conflicts and makes debugging easier.

# The variable is defined outside a function.
message = "I'm global!"  

def show_global():
    # You can access 'message' inside a function.
    controller.screen.print(message)
    controller.screen.next_row()

show_global()
# And you can access 'message' outside a function.
controller.screen.print(message)

By default, assigning a value to a variable inside a function creates a local variable. To modify a global variable inside a function, you must explicitly declare it using the global keyword.

# Define the global variable.
count = 0 

def increase_count():
    # Use the global keyword to let you modify the
    # global variable.
    global count
    count = count + 1
    controller.screen.print(f"Count: {count}")
    controller.screen.next_row()

increase_count()
increase_count()

Types of Data#

Python variables can store various types of data, each suited for different use cases. Below are the most commonly used types:

Integer#

An integer is a whole number.

distance = 50

drone.take_off(starting_altitude=500)
# Move the robot forward for the variable value in mm.
drone.climb_for(direction=DOWN, distance=distance, velocity=50, units=MM)
wait(2, SECONDS)

# Add to the variable and move forward the new value, 
# for 100mm total.
distance = distance + 50
drone.climb_for(direction=UP, distance=distance, velocity=50, units=MM)
wait(2, SECONDS)

drone.land()

Float#

A float is a decimal-point number.

# Store a value with decimal points.
raw_value = 0.88

# Print the decimal value as a percentage.
controller.screen.print(raw_value * 100, "%")

String#

A string is a sequence of characters, commonly used for text.

# Set the variable to a string then print the string.
message = "Ready!"
controller.screen.print(message)

Note: A string must always be enclosed within matching quotation marks, either single (') or double ("). You can use either style, but the opening and closing marks must match.

Boolean#

A Boolean represents True or False values.

# Set the state of the variable.
delivered = False

# Print different messages depending on the Boolean.
if delivered:
    controller.screen.print("Package delivered!")
else: 
    controller.screen.print("Delivering...")

Booleans can be changed at any point in the project.

# Print the value of the delivered variable
delivered = True
controller.screen.print(delivered)
wait(2,SECONDS)

# Clear the screen and print the value of the variable again
controller.screen.clear_screen(color=GREEN)
delivered = False
controller.screen.print(delivered)

NoneType#

NoneType represents the absence of a value in Python.

# Write what the controller's task should be as a string
current_task = None

# Check if a task is assigned
if current_task is None:
    controller.screen.print("No task!")
else:
    controller.screen.print(f"Task: {current_task}")

Range#

A range is a sequence of numbers, commonly used in loops to generate numeric sequences. It follows the format:

range(start, stop, step)

  • The start value is inclusive (the sequence begins here). This defaults to 0.

  • The stop value is exclusive (the sequence stops before this number).

  • The step determines how much each number increases (or decreases). This defaults to 1.

# Move back and forth four times then land.
drone.take_off(starting_altitude=500)
for i in range(4):
    drone.move_for(direction=0, distance=500, velocity=50, units=MM)
    wait(1, SECONDS)
    drone.move_for(direction=180, distance=500, velocity=50, units=MM)
    wait(1, SECONDS)
drone.land()

# Count by 2 starting at 1 and ending before 12.
for index in range(1, 12, 2): 
    # Print the values on the screen with each loop.
    controller.screen.print(index)
    controller.screen.next_row()

List#

A list is a versatile structure that stores multiple values in a single variable. Its contents can be modified, accessed, or iterated over easily.

# Define a list of colors.
colors = ["Red", "Green", "Blue"]

# Repeat for the number of items in the colors list.
for color in colors:
    # Print each color in order
    controller.screen.print(color)
    controller.screen.next_row()

Lists can be added to using append.

# Define a list of colors.
colors = ["Red", "Green", "Blue"]

# Append a new color to the list.
colors.append("Yellow")

# Repeat for the number of items in the colors list.
for color in colors:
    # Print each color in order
    controller.screen.print(color)
    controller.screen.next_row()

2D List#

A 2D list, or list of lists, is commonly used to represent grids, tables, or matrices. Each sublist represents a row or a specific grouping of data.

# Assign the values in the matrix 2D list.
matrix = [
    ["A", 1, "Red"],
    ["B", 2, "Orange"],
    ["C", 3, "Yellow"]
]
# Loop through each row.
for row in matrix: 
    # Loop through each column in the row.
    for element in row: 
        controller.screen.print(element, end=", ")
    controller.screen.next_row()

You can modify specific elements or even entire sublists within a 2D list:

# Assign the values in the matrix 2D list.
matrix = [
    ["A", 1, "Red"],
    ["B", 2, "Orange"],
    ["C", 3, "Yellow"]
]
# Modify the color (in column 2) in row 0.
matrix[0][2] = "Blue"

# Print the modified row from the matrix 2D list.
controller.screen.print(matrix[0])

Tuple#

A tuple is a sequences of items that cannot be changed after they are created. They are often used to group related values together.

# Define a tuple.
set_1 = (100, "Left")

# Print the tuple.
controller.screen.print(set_1)

Tuples are created using parentheses() rather than square brackets [].