此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Name a block of code
- A function is named code you can use again and again.
- Make one with
def name():and an indented body. - "Calling" the function by its name runs that code.
English
Give it inputs (parameters)
- The names in the brackets are parameters — the function's inputs.
- When you call it, you pass in arguments (the real values).
- A function can take more than one parameter.
English
def shout(word):
print(word.upper() + "!")
shout("hello")
English
Send back a result (return)
returnsends a value back to whoever called the function.- You can store that value or use it in an expression.
returnalso ends the function straight away.

English
def double(x):
return x * 2
result = double(5)
print(result)
English
return vs print
printonly shows something on the screen.returngives a value back that the rest of your code can use.- A function with no
returngives backNone.
English
In Cambridge pseudocode
- A
FUNCTIONreturns a value; aPROCEDUREjust does an action.
FUNCTION Add(A : INTEGER, B : INTEGER) RETURNS INTEGER
RETURN A + B
ENDFUNCTION
PROCEDURE Greet(Name : STRING)
OUTPUT "Hello, ", Name
ENDPROCEDURE
English
Common mistakes
- A function returns
Noneunless you writereturn; printing is not the same as returning. - Run a function with
():greet(), notgreet. - Define a function before you call it.
English
Now you try
- Define each function, then the checks will call it for you.
- Use
returnto send the answer back (do notprintit).
探索
Calling a function
A call pushes a frame with its arguments; return pops it.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function add(a, b) that 返回值 the sum of a and b.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function greet(name) that 返回值 the string Hello, then the name then !. So greet("Sam") 返回值 Hello, Sam!.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write a function biggest(a, b) that 返回值 the larger of the two values. If they are equal, return either one.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Write is_palindrome(word) that 返回值 True when the word reads the same backwards (like racecar), otherwise False.
点击“运行”查看此处输出。