變數#

介紹#

變數儲存數據,並允許您在整個程式中重複使用和操作數據。 Python 是一種動態類型語言,這表示您無需明確宣告變數的類型。相反,它會根據賦值自動推斷變數的類型。例如:

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

Python 也是強型別的,這表示如果不明確轉換,就無法對不相容的型別執行操作。例如:

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

要解決此類問題,您必須明確轉換類型(如果適用):

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

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

本 API 講解了 Python 中常見的變數類型。雖然清單並不詳盡,但涵蓋了您在實際工作中最可能使用的類型。

  • 局部變數 – 在函數內部宣告並僅在該範圍內使用;最適合臨時或孤立的值。

  • 全域變數 – 在任何函數外部宣告並在整個專案中使用;適合在函數之間共用資料。

  • 整數 – 用於計數、距離或任何沒有小數的整數。

  • 浮點數 – 有小數點的數字,適用於精確測量或計算。

  • 字串 – 文字值,用於訊息、標籤或顯示可讀輸出。

  • 布林值 – True 或 False 用於邏輯和決策的值。

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

  • 範圍 – 自動產生數字序列,最常用於迴圈。

  • 列表 – 可變的項目集合;適用於儲存物件或感測器讀數等值組。

  • 2D 清單 – 清單的清單;非常適合表示行、網格或類似表格的資料。

  • 元組 – 不可更改的固定值序列;適用於分組的、不變的資料。

聲明和分配變數#

要建立變量,只需使用 = 運算符為名稱賦值即可:

distance = 100

命名變數時,必須遵守以下規則:

  • 名稱不能包含特殊字元(例如感嘆號)。

  • 名稱不能以數字開頭。

  • 名稱中不能使用空格。

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

Local Variables#

局部變數是在函數或程式碼區塊內部定義的。它們只能在該函數或程式碼區塊的範圍內訪問,在其外部不可見。

def show_local():
    # This variable only exists inside this function.
    message = "I'm local!" 
    controller.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.
    controller.screen.print(message)
    controller.screen.next_row()

show_global()
# And you can access 'message' outside a function.
controller.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
    controller.screen.print(f"Count: {count}")
    controller.screen.next_row()

increase_count()
increase_count()

資料類型#

Python 變數可以儲存各種類型的數據,每種類型都適用於不同的用例。以下是最常用的類型:

Integer#

整數是正數或負數。

distance = 50

drone.take_off(climb_to=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#

浮點數 是小數。

# Store a value with decimal points.
raw_value = 0.88

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

String#

字串是字元序列,通常用於文字。

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

注意: 字符串必须始终用匹配的引号括起来,可以是单引号(’),也可以是双引号(”)。您可以使用任何一种样式,但开头和结尾标记必须匹配。

Boolean#

布林值表示 True 或 False 值。

# 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...")

布林值可以在專案的任何時候改變。

# 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 表示 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#

範圍 是一個數字序列,通常用於循環中產生數字序列。其格式如下:

range(start, stop, step)

成分

描述

start

可選。起始值包含起始值(序列從此處開始)。預設值為 0。

stop

停止值是唯一的(序列在此數字之前停止)。

step

可選。此步長決定每個數字增加(或減少)的幅度。預設值為 1。

# Move back and forth four times then land.
drone.take_off(climb_to=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#

列表(List)將一組項目儲存在一個變數中。您可以新增項目、刪除項目、變更項目,或在項目中逐一使用每個項目。當您想要將相關值(例如感測器讀數、顏色或物件名稱)放在一起時,清單非常有用。列表使用方括號 []

# 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()

使用 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#

二維列表,或稱為列表的列表,通常用於表示網格、表格或矩陣。每個子列表代表一行或一組特定的資料。

# 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()

您可以修改二維清單中的特定元素甚至整個子清單:

# 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#

元組是一組創建後不可更改的元素序列。它們通常用於將相關的值組合在一起。

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

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

元組是用圓括號 () 而不是方括號 []創建的。