變數#
介紹#
變數用於儲存數據,並允許你在整個程式中重複使用和操作這些數據。 Python 是一種動態類型語言,這意味著你不需要明確宣告變數的類型。相反,類型會根據賦值自動推論。例如:
angle = 90 # angle is an integer
dist = "Distance: " # dist is a string
steps = 2.5 # steps is a float
Python 也是強型別語言,這表示你不能對不相容的型別執行操作,除非明確地進行型別轉換。例如:
red_disks = 2 # red_disks is an integer
green_disks = "4" # green_disks is a string
result = red_disks + green_disks # Creates a TypeError
要解決此類問題,您必須在適當情況下明確轉換類型:
red_disks = 2 # red_disks is an integer
green_disks = "4" # green_disks is a string
# Convert green_disks to an integer before adding
result = int(green_disks) + red_disks
本 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!"
console.print(message)
def main():
show_local()
# Start threads — Do not delete
start_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
console.print(message)
console.new_line()
def main():
show_global()
# And you can access 'message' outside a function
console.print(message)
# Start threads — Do not delete
start_thread(main)
預設情況下,在函數內部給變數賦值會建立一個局部變數。要修改函數內部的全域變量,必須使用 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
console.print("Count: {}".format(count))
def main():
increase_count()
console.new_line()
increase_count()
# Start threads — Do not delete
start_thread(main)
資料類型#
Python 變數可以儲存多種類型的數據,每種類型都適用於不同的使用場景。以下是最常用的幾種類型:
Integer#
整數是正數或負數。
# Build Used: Super Code Base 2.0
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)
# Start threads — Do not delete
start_thread(main)
Float#
浮點數是帶小數點的數字。
def main():
# Store a value with decimal points
raw_value = 0.88
# Print the decimal value as a percentage
console.print(raw_value * 100, "%")
# Start threads — Do not delete
start_thread(main)
String#
字串是一系列字符,通常用於表示文字。
def main():
# Set the variable to a string then print the string
message = "Ready!"
console.print(message)
# Start threads — Do not delete
start_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#
布林值表示 True 或 False 值。
def main():
# Set the state of the variable
delivered = False
# Print different messages depending on the Boolean.
if delivered:
console.print("Package delivered!")
else:
console.print("Delivering...")
# Start threads — Do not delete
start_thread(main)
布林值可以在專案的任何階段進行更改。
def main():
# Print the value of the delivered variable
delivered = True
console.print(delivered)
console.new_line()
wait(2,SECONDS)
# Clear the screen and print the value of the variable again
console.clear()
delivered = False
console.print(delivered)
# Start threads — Do not delete
start_thread(main)
NoneType#
NoneType 表示 Python 中缺少某個值。
def main():
# No task is assigned yet
current_task = None
# Check if a task is assigned
if current_task is None:
console.print("No task!")
else:
console.print("Task: {}".format(current_task))
# Start threads — Do not delete
start_thread(main)
Range#
範圍 是一系列數字,常用於循環中產生數字序列。其格式如下:
range(start, stop, step)
成分 |
描述 |
|---|---|
|
可選。起始值包含起始值(序列從此處開始)。預設值為 0。 |
|
停止值是唯一的(序列在此數字之前停止)。 |
|
可選。此步長決定每個數字增加(或減少)的幅度。預設值為 1。 |
# Build Used: Super Code Base 2.0
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)
# Start threads — Do not delete
start_thread(main)
def main():
# 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
console.print(index)
console.new_line()
# Start threads — Do not delete
start_thread(main)
List#
列表(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
console.print(index)
console.new_line()
# Start threads — Do not delete
start_thread(main)
使用 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
console.print(index)
console.new_line()
# Start threads — Do not delete
start_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:
console.print(element, ", ")
console.new_line()
# Start threads — Do not delete
start_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
console.print(matrix[0])
# Start threads — Do not delete
start_thread(main)
Tuple#
元組是一組創建後不可更改的元素序列。它們通常用於將相關的值組合在一起。
def main():
# Define a tuple
set_1 = (100, "Left")
# Print the tuple
console.print(set_1)
# Start threads — Do not delete
start_thread(main)
元組是用圓括號 () 而不是方括號 []創建的。