変数#
導入#
変数はデータを格納し、プログラム全体でそのデータを再利用および操作できるようにします。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#
グローバル変数は、関数やブロックの外側で定義されます。そのため、関数内を含め、プログラム内のどこからでもアクセスして読み取ることができます。
注: グローバル変数はプロジェクト内のどこでも使用できます。これは便利な反面、バグの発見を困難にする可能性もあります。値が変更された場合、変更箇所を特定するためにプロジェクトの多くの部分を確認する必要があるかもしれません。値が必要な関数が1つだけの場合は、ローカル変数を使用してください。
# 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)
注: 文字列は必ず、シングルクォーテーション(’)またはダブルクォーテーション(”)のいずれかで囲む必要があります。どちらのスタイルでも使用できますが、開始クォーテーションと終了クォーテーションは一致している必要があります。
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を含みます(シーケンスはここから始まります)。デフォルト値は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#
リストは、1 つの変数にアイテムのグループを格納します。アイテムを追加、削除、変更したり、プロジェクトで各アイテムを 1 つずつ使用したりできます。リストは、センサーの読み取り値、色、オブジェクト名など、関連する値をまとめて保持したい場合に便利です。リストは角括弧 []を使用して作成します。
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#
2Dリスト、つまりリストのリストは、グリッド、テーブル、またはマトリックスを表すためによく使用されます。各サブリストは、行または特定のデータグループを表します。
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)
2Dリスト内の特定の要素、あるいはサブリスト全体を変更できます。
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)
Tuples are created using parentheses () rather than square brackets [].