变量#

监视变量#

要将变量的值添加到监视控制台,请使用 monitor_variable() 命令。

数值变量#

数字变量用于存储数值。

要为数字变量赋值,请使用“=”运算符。

数字变量的默认名称为“my_number”。命名数字变量时请遵循以下规则:

  • 名称不能使用特殊字符(例如感叹号)。

  • 名称不能以数字开头。

  • 名称中不能使用空格。

  • 该名称不能是 VEXcode VR 中的保留字(例如 Drivetrain)。

def main():
    # Create the numeric variable "drive_distance" and set it to 500.
    drive_distance = 500
    # Drive forward for the drive_distance's value in Millimeters.
    drivetrain.drive_for(FORWARD, drive_distance, MM)

字符串变量#

字符串变量用于存储字符串,即字符序列。字符可以包括数字、字母和符号。

要为字符串变量赋值,请使用 = 运算符。

字符串变量的默认名称为 my_string。命名字符串变量时请遵循以下规则:

  • 名称不能使用特殊字符(例如感叹号)。

  • 名称不能以数字开头。

  • 名称中不能使用空格。

  • 该名称不能是 VEXcode VR 中的保留字(例如 Drivetrain)。

def main():
    # Create the string variable "new_project".
    new_project = "New project has started."
    # Print the String value of "new_project".
    brain.print(new_project)

布尔变量#

布尔变量可以保存 True 或 False 值。

要为布尔变量赋值,请使用 = 运算符。

布尔变量的默认名称为 my_boolean。命名布尔变量时请遵循以下规则:

  • 名称不能使用特殊字符(例如感叹号)。

  • 名称不能以数字开头。

  • 名称中不能使用空格。

  • 该名称不能是 VEXcode VR 中的保留字(例如 Drivetrain)。

def main():
    # Create the boolean variable "reverse_drive".
    reverse_drive = True

    # Check the Boolean value from the variable "reverse_drive".
    if reverse_drive:
        # Drive reverse if True.
        drivetrain.drive(REVERSE)

    else:
        # Drive forward if False.
        drivetrain.drive(FORWARD)

    # Wait 5 seconds.
    wait(5, SECONDS)
    # Stop the drivetrain.
    drivetrain.stop()

数字列表#

列表变量用于在单个变量名中存储多个值。

List 变量的默认名称是:my_list = [0, 0, 0]

List 变量的命名规则与所有其他变量相同:

  • 名称不能使用特殊字符(例如感叹号)

  • 名称不能以数字开头

  • 名称不能使用空格

  • 该名称不能是 VEXcode VR 中的保留字(例如 Drivetrain)

如果值是数字,则逗号应紧跟在每个数字后面。

如果值是字符串,则逗号应位于引号之外。

可以使用索引访问列表变量中的数据元素。

def main():
    # Create the numeric list "drive_distance".
    drive_distance = [100, 200, 300]
    # Drive forward for 200 Millimeters.
    drivetrain.drive_for(FORWARD, drive_distance[2], MM)

二维数字列表#

与列表变量类似,二维列表变量用于在单个变量名中存储多个值。然而,二维列表变量可以存储多个列表。

2D 列表变量的默认名称是:

my_2d_list = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
]

2D List 变量的命名规则与所有其他变量相同:

  • 名称不能使用特殊字符(例如感叹号)

  • 名称不能以数字开头

  • 名称不能使用空格

  • 该名称不能是 VEXcode VR 中的保留字(例如 Drivetrain)

二维数组中的数据元素可以通过两个索引访问。索引表示值在 List 变量中的位置。要访问值,首先使用二维 List 的名称,然后使用方括号括起来的两个索引:my_2d_list[0][0]。第一个索引表示行,第二个索引表示列,从 0 开始。

def main():
    # Create the 2D numeric list "drive_distance".
    drive_distance = [
        [5, 10],
        [15, 20],
    ]

    # Drive forward for 10 inches.
    drivetrain.drive_for(FORWARD, drive_distance[0][1], INCHES)