变量#

介绍#

变量用于存储数据,并允许你在整个程序中重复使用和操作这些数据。Python 是一种动态类型语言,这意味着你不需要显式声明变量的类型。相反,类型会根据赋值自动推断。例如:

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

Python 也是强类型语言,这意味着你不能对不兼容的类型执行操作,除非显式地进行类型转换。例如:

blocks = 2                       # blocks is an integer
disks = "4"                      # disks is a string
result = blocks + disks  # Creates a TypeError

要解决此类问题,您必须在适当情况下显式转换类型:

blocks = 2  # blocks is an integer
disks = "4" # disks is a string

# Convert disks to an integer before adding
result = int(disks) + blocks

本 API 解释了 Python 中常见的变量类型。虽然并非详尽无遗,但它涵盖了你在实践中最可能用到的类型。

  • 局部变量 – 在函数内部声明,并且仅在该作用域内使用;最适合临时或隔离值。

  • 全局变量 – 在任何函数外部声明,并在整个项目中使用;非常适合在函数之间共享数据。

  • 整数 – 用于计数、距离或任何不带小数的整数。

  • Float – 带小数点的数字,用于精确测量或计算。

  • String – 文本值,用于消息、标签或显示可读输出。

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

  • NoneType – 表示“尚未有值”,通常用作占位符。

  • 范围 – 自动生成数字序列,最常用于循环中。

  • 列表 – 可变的项目集合;适合存储对象或传感器读数等值组。

  • 2D 列表 – 列表的列表;非常适合表示行、网格或表格状数据。

  • 元组 – 不可更改的固定值序列;适用于分组的、不变的数据。

声明和赋值变量#

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

distance = 100

命名变量时,必须遵守以下规则:

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

  • 名称不能以数字开头。

  • 名称中不能包含空格。

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

Local Variables#

局部变量是在函数或代码块内部定义的。它们只能在该函数或代码块的作用域内访问,在外部不可见。

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

def main():
    show_local()

# VR threads — Do not delete
vr_thread(main)

局部变量通常用于存储仅在特定函数或程序部分中相关的临时值。

Global Variables#

全局变量 定义在任何函数或代码块的外部。它们可以在程序中的任何位置访问和读取,包括函数内部。

注意: 全局变量 可以在程序的任何位置访问,这使得跨函数共享数据变得非常方便。然而,过度依赖全局变量可能会导致意想不到的副作用,因为程序中某个部分的变量更改可能会对其他部分产生不可预测的影响。因此,通常建议尽可能使用局部变量,因为它们将变量的作用域限制在定义它的特定函数中。这可以降低冲突的可能性,并使调试更加容易。

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

def show_global():
    # You can access 'message' inside a function
    brain.print(message)
    brain.new_line()

def main():
    show_global()
    # And you can access 'message' outside a function
    brain.print(message)

# VR threads — Do not delete
vr_thread(main)

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
    brain.print("Count: {}".format(count))
    brain.new_line()

def main():
    increase_count()
    increase_count()

# VR threads — Do not delete
vr_thread(main)

数据类型#

Python 变量可以存储多种类型的数据,每种类型都适用于不同的使用场景。以下是最常用的几种类型:

Integer#

整数是指不带正负号的数。

def main():
    distance = 100

    # Move the robot forward for the variable value in mm
    drivetrain.drive_for(FORWARD, distance, MM)

    # Add to the variable and move forward the new value, 
    # for 200mm total
    wait(1, SECONDS)
    distance = distance + 100
    drivetrain.drive_for(FORWARD, distance, MM)

# VR threads — Do not delete
vr_thread(main)

Float#

浮点数是带小数点的数字。

def main():
    # Store a value with decimal points
    raw_value = 0.88

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

String#

字符串是一系列字符,通常用于表示文本。

def main():
    # Set the variable to a string then print the string
    message = "Ready!"
    brain.print(message)

# VR threads — Do not delete
vr_thread(main)

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.

def main():
    # Set the state of the variable
    delivered = False

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

# VR threads — Do not delete
vr_thread(main)

布尔值可以在项目的任何阶段进行更改。

def main():
    # Print the value of the delivered variable
    delivered = True
    brain.print(delivered)
    wait(2,SECONDS)

    # Clear the screen and print the value of the variable again
    brain.clear()
    delivered = False
    brain.print(delivered)

# VR threads — Do not delete
vr_thread(main)

NoneType#

NoneType 表示 Python 中缺少某个值。

def main():
    # Write what the robot's task should be as a string
    current_task = None

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

# VR threads — Do not delete
vr_thread(main)

Range#

范围 是一系列数字,常用于循环中生成数字序列。其格式如下:

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.

def main():
    # Drive and turn 4 times to move in a square
    for index in range(4):
        drivetrain.drive_for(FORWARD, 100, MM)
        drivetrain.turn_for(RIGHT, 90, DEGREES)

# VR threads — Do not delete
vr_thread(main)

def main():
    # Count by 2 starting at 1 and ending before 12
    for index in range(1, 12, 2): 
        # Print the values with each loop
        brain.print(index)
        brain.new_line()

# VR threads — Do not delete
vr_thread(main)

List#

列表是一种用途广泛的数据结构,它将多个值存储在单个变量中。列表的内容可以轻松地进行修改、访问或遍历。

def main():
    # Define a list of colors
    colors = ["Red", "Green", "Blue", "Purple"]

    # Repeat for the number of items in the colors list
    for index in colors:
        # Print each color in order
        brain.print(index)
        brain.new_line()

# VR threads — Do not delete
vr_thread(main)

Lists can be added to using append.

def main():
    # Define a list of colors
    colors = ["Red", "Green", "Blue", "Purple"]

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

    # Repeat for the number of items in the colors list
    for index in colors:
        # Print each color in order
        brain.print(index)
        brain.new_line()

# VR threads — Do not delete
vr_thread(main)

2D List#

二维列表(或列表的列表)通常用于表示网格、表格或矩阵。每个子列表代表一行或一组特定的数据。

def main():
    # 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: 
            brain.print(element, ", ")
        brain.new_line()

# VR threads — Do not delete
vr_thread(main)

您可以修改二维列表中的特定元素,甚至整个子列表:

def main():
    # 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 
    brain.print(matrix[0])

# VR threads — Do not delete
vr_thread(main)

Tuple#

元组是一组元素的序列,创建后不能更改。它们通常用于将相关的值组合在一起。

def main():
    # Define a tuple
    set_1 = (100, "Left")

    # Print the tuple
    brain.print(set_1)

# VR threads — Do not delete
vr_thread(main)

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