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.
中文
函数是一个有名字的代码块
- 函数(function)是一段有名字的代码,可以反复运行。
- 用
def定义一次,然后用名字调用(call)它。 - 这样就不用重复写代码,程序也更整洁。
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.
中文
参数把数据传进来
- 参数(parameter)是函数接收的值。
- 把它放进括号里,调用时传入一个实参(argument)。
- 让参数数量少一些,函数才好读。
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把一个值交回去。 - 一段只做事、不返回任何值的代码块叫做过程(procedure)。
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. · 调用会运行函数体;return 交回一个值。
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. · 写一个函数 double(n),返回 n 乘以 2。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a function is_even(n) that returns True when n is even, otherwise False. · 写一个函数 is_even(n),当 n 是偶数时返回 True,否则返回 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 ****. · 写一个过程 print_stars(n),打印一行 n 个星号(*),然后用 4 调用它,使它打印 ****。
Click Run to see the output here. · 点击“运行”查看此处输出。