機能#
導入#
関数はPythonプログラミングの基本的な構成要素であり、コードスニペットを再利用可能で効率的なコードセクションにパッケージ化し、特定のタスクを実行するように設計されています。関数はプログラム内で複数回呼び出すことができるため、コードの構成が容易になり、コードの重複を避けることができます。また、関数を使用することでコードのデバッグも容易になります。
重要: 関数を定義するだけでは実行されません。start_thread を使用して新しいスレッドで関数を開始し、イベントやコールバックを待つことなくプロジェクトの開始時にすぐに実行を開始します。
defは関数を定義します。returnを返します。関数の出力をメインプログラムに返します。
使用法:
def function_name(parameters):
# Code to execute when the function is called
return result # Optional, used to return a value
パラメータ |
説明 |
|---|---|
|
関数に付ける名前。 |
|
オプション。関数呼び出し時に入力値を受け取る変数。これにより、関数にデータを渡すことができます。 |
|
オプション。関数が呼び出し元に結果を返すようにします。関数に return ステートメントが含まれていない場合、デフォルトでは |
注: 関数は呼び出される前に必ず定義されていなければなりません。
関数の定義と呼び出し#
Functions with No Parameters#
関数が入力値を必要としない場合は、引数なしで定義できます。
def greeting():
console.print("Hello!")
def main():
# Call the greeting function
greeting()
# Start threads — Do not delete
start_thread(main)
Functions with Parameters#
関数にパラメータを追加することもできます。これにより、関数が動作するために必要な情報を渡すことができます。
# Build Used: Super Code Base 2.0
def move_square(moves):
for index in range(moves):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Call the move_square function
move_square(4)
# Start threads — Do not delete
start_thread(main)
Functions with Default Arguments#
デフォルト引数とは、関数呼び出し時にその引数の値が指定されていない場合に、デフォルト値が使用されるパラメータのことです。
# Build Used: Super Code Base 2.0
def move_square(moves=4):
for index in range(moves):
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def main():
# Call the move_square function
move_square()
# Start threads — Do not delete
start_thread(main)
Return Values from Functions#
関数は、 return キーワードを使用して呼び出し元にデータを返すことができます。これにより、出力を取得してプログラム内で使用できます。
def times_two(number):
return number * 2
def main():
# Display the return value
console.print(times_two(2))
# Start threads — Do not delete
start_thread(main)
スレッドを開始する#
start_thread は、関数を新しいスレッドで開始し、プロジェクトの開始時にすぐに実行を開始します。
start_thread が複数使用される場合、関数は並行して実行されます。
Usage:
start_thread(function)
パラメータ |
説明 |
|---|---|
|
以前に定義された関数の名前。 |
# Build Used: Super Code Base 2.0
def move_square():
# Move in a square path
while True:
drivetrain.drive_for(FORWARD, 150)
drivetrain.turn_for(RIGHT, 90)
def led_lights():
# Blink LED lights
while True:
bumper.set_color(GREEN)
wait(0.5, SECONDS)
bumper.set_color(RED)
wait(0.5, SECONDS)
# Start threads — Do not delete
start_thread(move_square)
start_thread(led_lights)