Procedures & functions
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
English
A function is a named block
- A function is a named block of code you can run again and again.
- Define it once with
def, then call it by name. - This avoids repeating yourself and keeps programs tidy.
日本語
関数は名付けられたブロックです
- 関数は、再度実行可能な名付けられたコードブロックです。
defで一度定義し、名前で呼び出します。- これにより重複を避け、プログラムを整理できます。
def greet():
print("Hello!")
greet()
greet()
English
Parameters pass data in
- A parameter is a value the function receives.
- Put it in the brackets, and pass an argument when you call.
- Keep the number of parameters small so the function stays easy to read.
日本語
パラメータはデータを渡す
- パラメータは関数が受け取る値です。
- 括弧内に書き、呼び出す際に引数を渡します。
- パラメータの数を少なく保ち、関数の可読性を維持してください。
def greet(name):
print("Hello, " + name)
greet("Ada")
greet("Sam")
English
Functions return a value
- A function hands a value back with
return. - A block that only does something and returns nothing is a procedure.
日本語
関数は値を返します
- 関数は
returnを使って値を戻します。 - 単に作業を行って何も返さないブロックはプロシージャと呼ばれます。
def square(n):
return n * n
answer = square(6)
print(answer) # 36
Explore · 探索
Call and return
Calling runs the function's body; return hands a value back.
English
In the exam: PROCEDURE and FUNCTION
- Pseudocode separates a
PROCEDURE(no result) from aFUNCTION(returns a value).
日本語
試験対策: PROCEDURE と FUNCTION
- 疑似コードでは、
PROCEDURE(結果なし)とFUNCTION(値を返す)を区別します。
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
English
Common mistakes
- A function returns a value with
return; a procedure just does a job. - Call it with
(). - Parameters receive the arguments in order.
日本語
よくあるミス
- 関数は
returnで値を返し、プロシージャは単に作業を行います。 ()を用いて呼び出します。- パラメータは順序に従って引数を受け取ります。
English
Now you try
- Write each function — it is then called for you in the check.
- Press Check answer to test your code.
日本語
あなたも試してみよう
- 各関数を書き、チェック時に自動で呼び出されるようにします。
- 回答を確認 を押してコードを試してください。
Write a function double(n) that returns n times 2.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write a function is_even(n) that returns True when n is even, otherwise False.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write a procedure print_stars(n) that prints a line of n star (*) characters, then call it with 4 so it prints ****.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。