Функции, вызовы и возвращаемые результаты
Введено
6:37
Основы программирования
Every program in this course is complete and runnable: type it, run it, then change one line. The whole skill is a loop. First predict what the code will do…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| function/ˈfʌŋkʃn/ | функция |
| side effect/saɪd ɪˈfekt/ | побочный эффект |
| contract/ˈkɒntrækt/ | контракт |
| parameter/pəˈræmɪtə/ | формальный параметр |
| argument/ˈɑːɡjuːmənt/ | фактический аргумент |
| call frame/kɔːl freɪm/ | кадр вызова |
| local variable/ˈləʊkl ˈveərɪəbl/ | локальная переменная |
| scope/skəʊp/ | область видимости |
| decomposition/ˌdiːkɒmpəˈzɪʃn/ | декомпозиция |
Give each function one clear job
- A function 函数 is a named task. Before you write the body, state its inputs, the result it returns and any side effect 副作用, such as printing.
- A contract 契约 says what callers may pass in and what the function promises in return. Here, amounts are whole pence: integers that are zero or more.
def add_fee(amount):
"""Return amount plus a fixed fee of 3 pence."""
return amount + 3
add_fee(8) gives 11. It prints nothing. Keeping the calculation separate from the display lets other functions reuse the result.
Какой контракт позволяет использовать сумму с учетом комиссии непосредственно в других вычислениях?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Возвращаемый результат может использоваться в выражении; вывод на экран является отдельным побочным эффектом.
Parameters and arguments
- In the definition,
amountis a parameter 形参. In the calladd_fee(8), the value8is the argument 实参. Python works out each argument before the function body runs. - The call makes the parameter name point at the argument's value. It does not copy the value, and it does not link the caller's variable to the parameter.
amount = 4
result = add_fee(amount * 2)
print(amount, result)
The argument amount * 2 gives 8, so inside the call amount is 8. The returned 11 is stored in result. Outside the function, amount is still 4, so the output is 4 11.
Соотнесите каждый термин с его ролью в функции add_fee(8).
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Аргумент вычисляется при вызове; его объект привязывается к параметру; возвращение передаёт результат обратно.
Each call has its own frame
- A call frame 调用帧 holds one running function call, with its parameters and local names. When one function calls another, the caller waits for the returned value.
- Read this program in the order it runs: main program →
twice→add_fee→ back totwice→ back to the main program. The arrows show the order of the calls, not how memory is laid out.
def twice(amount):
subtotal = amount * 2
return add_fee(subtotal)
amount = 4
result = twice(amount)
print(amount, result)

Follow the calls and returns in the figure. The frames show each name's value at the moment add_fee is running.
Трассировка вызова twice(4), внутри которого вызывается add_fee(8)
Разделяйте локальные привязки переменных и возвращаемые значения.
Расположите эти события в порядке, следующем за result = twice(4).
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Вложенный вызов завершается до того, как twice может завершить своё выражение return.
Какое целое число привязано к amount внутри add_fee во время этого вложенного вызова?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
twice рассчитывает subtotal как 4 умножить на 2, затем передаёт это значение 8 в add_fee.
Return a result; print a message
returnends the call and gives a value back to the caller. A function that reaches its end withoutreturngives backNone.printonly shows output, and it returnsNoneitself. Printing a result inside a function does not return it.
def show_fee(amount):
print(amount + 3)
value = show_fee(8)
print(value)
This prints 11, then None, on separate lines. If the caller needs the number, use return amount + 3 and let the caller decide whether to print it.
show_fee выводит 11, но не имеет оператора return. Что хранится в value?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Выход в конце функции Python возвращает None, независимо от выведенного вывода.
Names inside and outside a function
- A local variable 局部变量 belongs to one function call. Its scope 作用域 is the part of the program where the name can be used; a function cannot see another function's local names.
- Giving a parameter a new value changes only the local name. A variable with the same name in the caller is not changed.
def increase(amount):
amount = amount + 1
return amount
amount = 4
new_amount = increase(amount)
print(amount, new_amount)
The output is 4 5. Both names start by pointing at 4; the assignment inside the function moves only the local name. To change the outside amount, write amount = increase(amount).
После new_amount = increase(amount), какое значение всё ещё хранит модульная переменная amount?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Была переназначена только локальная переменная функции; вызывающий код не выполнял присваивания для amount.
Decompose a calculation into testable pieces
- Decomposition 分解 splits a large task into small jobs, each with a clear contract. For an order: work out the item subtotal, add the fee, then display the total.
- Test the calculations directly, including a quantity of zero and more than one item. Checking the user's input can be a separate function.
def item_subtotal(unit_pence, quantity):
return unit_pence * quantity
def order_total(unit_pence, quantity):
return add_fee(item_subtotal(unit_pence, quantity))
order_total(5, 2) gives 13; order_total(5, 0) gives 3, because the fee is always added. If an empty order should cost nothing, change the contract and the code together.
При указанном договоре с фиксированной комиссией, что возвращает order_total(5, 0) в пенсах?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Сумма подзаказа равна нулю, но add_fee всё равно добавляет 3. Пустые заказы требуют иного договора.
Trace the whole call before trusting the answer
- Trace the arguments, the parameters, the local calculations and the returned values. Then check the caller's variables and the printed output separately.
- Passing an argument does not copy it. A list passed to a function can be changed through the parameter; lesson 0105 shows this with lists.
A correct printed number does not prove a correct returned value. Check the value directly, for example assert order_total(5, 2) == 13, and check the printed output separately.
Language references: Python functions and name binding and scope.
Вызов функции Python автоматически копирует каждый аргумент-объект.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Параметры привязываются к предоставленным объектам. Копирование должно запрашиваться явно при необходимости.
Recap
- A contract says what goes in and what comes back; one function, one job.
- A call makes the parameter name point at the argument's value; local names stay inside their call.
return |
print |
|
|---|---|---|
| Gives the caller | the value | None |
| Shows on screen | nothing | the text |
| Can a test check it? | yes, with assert |
not directly |
Что пошло не так? Это увидит только команда сайта.