变量#

简介#

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

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

Python 也是强类型的,这意味着如果不显式转换,就无法对不兼容的类型执行操作。例如:

sports_balls = 2                 # sports_balls is an integer
barrels = "4"                    # barrels is a string
result = barrels + sports_balls  # Creates a TypeError

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

sports_balls = 2   # sports_balls is an integer
barrels = "4"      # barrels is a string

# Convert barrels to an integer before adding
result = int(barrels) + sports_balls

此 API 解释了 Python 中常见的变量类型。虽然并非详尽无遗,但它涵盖了您在实际工作中最可能使用的类型。

  • 局部变量 – 在函数内部声明并仅在该范围内使用;最适合临时或独立的值。

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

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

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

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

  • Boolean – 用于逻辑和决策的 TrueFalse 值。

  • NoneType – 表示 Python 中不存在某个值。

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

  • [* 列表 *] (#list) –可更改的项目集合;适用于存储对象或传感器读数等值组。

  • [* * 2D列表* *] (#2d-list) –列表列表;非常适合表示行、网格或类似表格的数据。

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

声明和分配变量#

要创建变量,只需使用 = 运算符为名称赋值:

distance = 100

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

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

  • 名称不能以数字开头。

  • 名称中不能使用空格。

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

Local Variables#

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

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

show_local()

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

Global Variables#

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

**注意:**全局变量可以在项目中的任何位置使用。这虽然方便,但也可能导致错误更难查找。如果变量值发生变化,您可能需要检查项目的多个部分才能找到变化的位置。如果只有一个函数需要某个值,请使用局部变量。

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

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

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

默认情况下,为函数内的变量赋值会创建一个局部变量。要* 修改 *函数内的全局变量,必须使用 global 关键字显式声明它。

# 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
    robot.screen.print(f"Count: {count}")
    robot.screen.next_row()

increase_count()
increase_count()

数据类型#

Python 变量可以存储各种类型的数据,每种类型都适用于不同的用例。以下是最常用的类型:

Integer#

整数是正数或负数。

distance = 50

# Move the robot forward for the variable value in mm
robot.move_for(distance, 0)

# Add to the variable and move forward the new value, for 100mm total
distance = distance + 50
robot.move_for(distance, 0)

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
robot.screen.print(raw_value * 100, "%")

String#

string 是一个字符序列,通常用于文本。

# Set the variable to a string then print the string
message = "Ready!"
robot.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:
    robot.screen.print("Package delivered!")
else: 
    robot.screen.print("Delivering...")

布尔值可以在项目的任何时候改变。

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

# Clear the screen and print the value of the variable again
robot.screen.clear_screen(Color.BLACK)
delivered = False
robot.screen.print(delivered)

NoneType#

NoneType represents the absence of a value in Python.

# 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:
    robot.screen.print("No task!")
else:
    robot.screen.print(f"Task: {current_task}")

Range#

范围 是一个数字序列,通常在循环中用于生成数值序列。它遵循以下格式:

range(start, stop, step)

组成部分

描述

start

可选。起始值(包含),序列从此处开始。默认值为 0。

stop

结束值(不包含),序列在此数字之前停止。

step

可选。此步长决定每个数字增加(或减少)的幅度。默认值为 1。

# Drive and turn 4 times to move in a square
for index in range(4):
    robot.move_for(50, 0)
    robot.turn_for(RIGHT, 90)

# 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
    robot.screen.print(index)
    robot.screen.next_row()

List#

列表将一组项目存储在一个变量中。你可以在项目中添加项目、移除项目、更改项目,或者一次使用一个项目。当你希望将相关值保存在一起时,如传感器读数、颜色或对象名称,列表非常有用。列表使用方括号 [] 创建。

# 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
    robot.screen.print(index)
    robot.screen.next_row()

使用 append 向列表中添加项目。

# 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
    robot.screen.print(index)
    robot.screen.next_row()

2D List#

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

# 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: 
        robot.screen.print(element, ", ")
    robot.screen.next_row()

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

# 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 
robot.screen.print(matrix[0])

Tuple#

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

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

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

元组是使用括号 () 而不是方括号 []创建的。