變數#
介紹#
變數用於儲存數據,並允許你在整個程式中重複使用和操作這些數據。 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 中常見的變數類型。雖然並非詳盡無遺,但它涵蓋了你在實踐中最可能使用的類型。
局部變數 – 在函數內部聲明,並且僅在該作用域內使用;最適合臨時或隔離值。
全域變數 – 在任何函數外部聲明,並在整個專案中使用;非常適合在函數之間共享資料。
整數 – 用於計數、距離或任何不含小數的整數。
Float – 帶小數點的數字,用於精確測量或計算。
String – 文字值,用於訊息、標籤或顯示可讀輸出。
布林值 –
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!"
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#
浮點數是指帶小數點的數字。
# Store a value with decimal points
raw_value = 0.88
# Print the decimal value as a percentage
robot.screen.print(raw_value * 100, "%")
String#
字串是一系列字符,通常用於表示文字。
# Set the variable to a string then print the string
message = "Ready!"
robot.screen.print(message)
注意: 字符串必须始终用匹配的引号括起来,可以是单引号(’),也可以是双引号(”)。您可以使用任何一种样式,但开头和结尾标记必须匹配。
Boolean#
布林值表示 True 或 False 值。
# 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 表示 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)
成分 |
描述 |
|---|---|
|
可選。起始值包含起始值(序列從此處開始)。預設值為 0。 |
|
停止值是唯一的(序列在此數字之前停止)。 |
|
可選。此步長決定每個數字增加(或減少)的幅度。預設值為 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#
列表(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)
元組是用圓括號 () 而不是方括號 []創建的。