変数#
導入#
変数はデータを格納し、プログラム全体でそのデータを再利用および操作できるようにします。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でよく使われる変数型について説明します。網羅的なリストではありませんが、実際に使用する可能性の高い型を網羅しています。
ローカル変数 – 関数内で宣言され、そのスコープ内でのみ使用されます。一時的な値や隔離された値に最適です。
グローバル変数 – どの関数の外側でも宣言され、プロジェクト全体で使用されます。関数間でデータを共有するのに適しています。
整数 – 小数点を含まない、数えたり、距離を測ったりするために使用される整数。
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!"
controller.screen.print(message)
show_local()
ローカル変数は、特定の関数内またはプログラムの一部内でのみ有効な一時的な値を格納するためによく使用されます。
Global Variables#
グローバル変数は、関数やブロックの外側で定義されます。そのため、関数内を含め、プログラム内のどこからでもアクセスして読み取ることができます。
注: グローバル変数はプロジェクト内のどこでも使用できます。これは便利な反面、バグの発見を困難にする可能性もあります。値が変更された場合、変更箇所を特定するためにプロジェクトの多くの部分を確認する必要があるかもしれません。値が必要な関数が1つだけの場合は、ローカル変数を使用してください。
# 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)
コンポーネント |
説明 |
|---|---|
|
オプション。開始値は0を含みます(シーケンスはここから始まります)。デフォルト値は0です。 |
|
停止値は排他的です(シーケンスはこの数値より前に停止します)。 |
|
オプション。ステップは、各数値がどれだけ増加(または減少)するかを決定します。デフォルト値は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#
リストは、1 つの変数にアイテムのグループを格納します。アイテムを追加、削除、変更したり、プロジェクトで各アイテムを 1 つずつ使用したりできます。リストは、センサーの読み取り値、色、オブジェクト名など、関連する値をまとめて保持したい場合に便利です。リストは角括弧 []を使用して作成します。
# 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#
2Dリスト、つまりリストのリストは、グリッド、テーブル、またはマトリックスを表すためによく使用されます。各サブリストは、行または特定のデータグループを表します。
# 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()
2Dリスト内の特定の要素、あるいはサブリスト全体を変更できます。
# 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)
Tuples are created using parentheses () rather than square brackets [].