此页面需较新浏览器(支持 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.
English
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.
English
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.

English
def square(n):
return n * n
answer = square(6)
print(answer) # 36
探索
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).
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.
English
Now you try
- Write each function — it is then called for you in the check.
- Press Check answer to test your code.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write a 功能 double(n) that 返回值 n times 2.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write a function is_even(n) that returns True when n is even, otherwise False.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write a procedure print_stars(n) that prints a line of n star (*) characters, then call it with 4 so it prints ****.
点击“运行”查看此处输出。