Functions · 函数
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.
给一段代码起个名字
- 函数(function)是一段有名字、可以反复使用的代码。
- 用
def name():加上缩进的函数体来定义它。 - 用名字"调用"这个函数,就会运行那段代码。
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.
给它输入(参数)
- 括号里的名字是参数(parameter)—— 函数的输入。
- 调用它时,你传入实参(argument,真正的值)。
- 一个函数可以有多个参数。
def shout(word):
print(word.upper() + "!")
shout("hello")
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.
返回一个结果(return)
return会把一个值返回给调用它的地方。- 你可以存下这个值,或在表达式里使用它。
return还会立刻结束这个函数。
def double(x):
return x * 2
result = double(5)
print(result)
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.
return 与 print 的区别
print只是把内容显示在屏幕上。return会返回一个值,让后面的代码可以使用。- 没有
return的函数会返回None。
In Cambridge pseudocode
- A
FUNCTIONreturns a value; aPROCEDUREjust does an action.
用剑桥伪代码表示
FUNCTION会返回一个值;PROCEDURE只是执行一个动作。
FUNCTION Add(A : INTEGER, B : INTEGER) RETURNS INTEGER
RETURN A + B
ENDFUNCTION
PROCEDURE Greet(Name : STRING)
OUTPUT "Hello, ", Name
ENDPROCEDURE
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.
常见错误
- 没有写
return,函数就返回None;打印不等于返回。 - 用
()运行函数:greet(),不是greet。 - 先定义函数再调用它。
Now you try
- Define each function, then the checks will call it for you.
- Use
returnto send the answer back (do notprintit).
现在轮到你
- 定义好每个函数,检查会替你调用它。
- 用
return把答案返回(不要用print打印)。
Calling a function · 调用一个函数
A call pushes a frame with its arguments; return pops it. · 调用会压入一个栈帧(带参数);return 会弹出它。
Write a function add(a, b) that returns · 返回值 the sum of a and b. · 编写一个函数 add(a, b),返回 a 与 b 的和。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a function greet(name) that returns · 返回值 the string Hello, then the name then !. So greet("Sam") returns · 返回值 Hello, Sam!. · 编写一个函数 greet(name),返回字符串 Hello, 、名字、再加 !。即 greet("Sam") 返回 Hello, Sam!。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a function biggest(a, b) that returns · 返回值 the larger of the two values. If they are equal, return either one. · 编写一个函数 biggest(a, b),返回两个值中较大的那个。如果两者相等,返回其中之一即可。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write is_palindrome(word) that returns · 返回值 True when the word reads the same backwards (like racecar), otherwise False. · 编写 is_palindrome(word):如果这个单词倒过来读也一样(比如 racecar),就返回 True,否则返回 False。
Click Run to see the output here. · 点击“运行”查看此处输出。