Python functions and modules

Advanced

def defines a function, parameters are its inputs, return hands back the result; import brings in modules (math for roots, random for dice); write once, call anywhere.

For:Secondary 2 Information & Communication Technology · Unit:Algorithms & programming · Lesson 6 of 12 in the learning path

After this lesson, you can:
  • def defines; the function runs only when called with brackets.
  • Parameters are the inputs; return hands back the result.
  • print displays; return delivers values you can keep calculating with.
文體:編程教學課有聲朗讀

文體小知識:編程教學課每個概念都配一段可以親手試的代碼例子,照住輸入、改一改,最快學會。

資訊及通訊科技Information & Communication Technology

§Text Passage

1A function is a named, reusable block of code. Define it with def: def greet(name): print("Hello, " + name). Anywhere afterwards, greet("Mary") prints 'Hello, Mary' — write once, use forever. A defined but never-called function does nothing.

2The name in brackets is a parameter — the function's input. A function can hand a result back with return: def area(w, h): return w * h. After result = area(3, 4), result is 12. A returned value can feed further calculations (area(3, 4) * 2 gives 24) — something print cannot do.

3A module is a library written by others: after import math you can use math.sqrt(16) for the square root (4.0) and math.pi for the circle constant; after import random, random.randint(1, 6) rolls a die (a random integer from 1 to 6). Stand on others' shoulders instead of writing everything yourself.

4Why functions? Suppose a program must average three subjects for each of 20 students: write the maths once as average(scores), then one line per student — no pasting the same block 20 times. Functions make programs shorter, easier to fix and easier to test: change one line inside, every call updates.

1Summary 重點摘要

def defines a function, parameters are its inputs, return hands back the result; import brings in modules (math for roots, random for dice); write once, call anywhere.

2Vocabulary cards Vocabulary

F
Function函式

A named, reusable block of code that takes inputs and may return a result.

d
def定義關鍵字

The Python keyword for defining a function: def name(parameters):.

P
Parameter參數

The variable in the brackets at definition time — the function's input, e.g. name in def greet(name).

A
Argument引數

The actual value supplied at call time, e.g. "Mary" in greet("Mary").

R
Return value回傳值

The result a function hands back with return, ready for further use.

C
Call呼叫

Running a function by name with brackets and arguments, e.g. greet("Mary").

M
Module模組

A pre-written library such as math or random, available after importing.

i
import引入

The keyword that loads a module, e.g. import math before using math.sqrt.

r
random.randint()隨機整數函數

Returns a random integer including both ends, e.g. random.randint(1, 6) rolls a die.

3Step by step Steps

  1. Defining and calling your first functionA function is a named, reusable block of code, defined with def: def hello(): with print("Hello!") indented on the next line. Defining does not run the body — calling hello() prints Hello!. The grammar: the def keyword, a name, brackets, a colon, and an indented body. Write common calculations or displays as functions, and anywhere later you simply type the function's name: define once, use everywhere.
  2. Parameters: the function's inputThe name inside the brackets is a parameter — the function's input. def greet(name): print("Hello, " + name) defines a parameterised function; greet("Mary") prints 'Hello, Mary' and greet("Peter") prints 'Hello, Peter'. One function, different inputs, different results — like a vending machine dispensing different drinks for different choices. There can be several parameters, as in def area(w, h), called as area(3, 4) in order: the first argument pairs with 3 and the second with 4.
  3. return: handing the result backThe return statement hands a result back to the caller: after def area(w, h): return w * h, the line x = area(3, 4) makes x equal 12. The returned value keeps working: area(3, 4) * 2 gives 24, and area(3, 4) + area(2, 5) gives 22. Note that nothing after return inside the function runs, because the function has already ended. Return is the formal channel for a function to deliver its output, letting functions link like parts into larger programs.
  4. return versus printreturn and print are easily confused. print only displays on the screen — the value never comes back to the program; return is what hands the value back. Contrast: with def f(): return 5 you may write y = f() + 1 and y is 6, because f() delivered 5; but with def g(): print(5), the line y = g() + 1 fails, since g only displayed and delivered nothing. The rule: print is for eyes, return is for the program; whenever a result must feed further calculation, return is required.
  5. The math module: ready-made toolsA module is a library written by others, usable right after import. After import math: math.sqrt(16) computes the square root, 4.0; math.pi is the circle constant ≈ 3.14159; the area of a radius-3 circle is math.pi * 3 * 3 ≈ 28.27. No need to invent your own square-root method — standing on other people's shoulders is exactly the value of modules. Also common are the rounding helpers math.ceil and math.floor, and later trigonometry work uses the math module as standard equipment.
  6. The random module: simulating chanceAfter import random you can simulate random events. random.randint(1, 6) rolls a die, returning a random whole number from 1 to 6 each time; roll ten times with for i in range(10): print(random.randint(1, 6)). random.choice(["apple", "banana", "orange"]) picks one item from the list at random — a ready-made classroom lucky draw — and random.shuffle scrambles a list like shuffling cards. Lucky draws, randomly wandering game enemies and statistical simulations all stand on the random module.
  7. Functions plus calls: power multipliedFunctions multiply their power through calls. After def average(nums): return sum(nums) / len(nums): print(average([80, 90])) gives 85.0; print(average([70, 75, 95])) gives 80.0; and unlimited calls need no rewriting. A real scene: thirty students with three subjects each, one line of average(that student's marks) per student completes the statistics; if the method changes — say dropping the lowest mark first — one line inside the function updates every call at once. That is the core advantage of function-style coding.

4Diagrams Diagrams

Python 函式:一塊可重用嘅積木 Functionsdef make_tea(cups):return "沖好 " + str(cups) + " 杯茶"print(make_tea(3))↑ def 定義 cups 係參數 return 交返結果寫一次 make_tea(),之後無論要 3 杯定 100 杯,一句 call 搞掂好處:唔使重複寫同一段碼;改一處,全部生效——模組化思維模組 module:人哋寫好嘅函式庫(例如 random 隨機數),import 就用得
Fig. 1: Python functions

5Worked example Example

Example: write a function max2(a, b) that returns the larger of two numbers, then use it on 17 and 9.

  1. def max2(a, b): — define with two parameters, a and b.
  2. Body: if a > b: return a, otherwise return b.
  3. Call: print(max2(17, 9)) — since 17 > 9 holds, it returns a = 17.
  4. Try the edge: print(max2(9, 9)) — a > b fails, so return b = 9; for equal numbers the result is still 9, correct.
  5. Answer: def max2(a, b): if a > b: return a, else return b; max2(17, 9) = 17.

6Common mistakes Mistakes

✗ Once def is written, the function runs itself.
✓ def only defines; it runs when called, e.g. hello().
✗ The function body needs no indentation.
✓ Python uses indentation to mark what belongs to the function or loop; missing it causes a syntax error.
✗ print and return are the same thing.
✓ print only displays; return hands the value back for further maths. To reuse a result you need return.
✗ greet(name) and greet("Mary") are the same call.
✓ At definition the brackets hold a parameter (name); at call they hold an actual value ("Mary") — calls need real values.
✗ You can use math.sqrt without importing.
✓ Modules must be imported first (e.g. import math) or a NameError appears.

7Quick check Quick check

Q1Which keyword defines a function? A. function B. def C. define

Q2Given def add(a, b): return a + b, what is add(3, 5)?

Q3Inside a function, what hands a result back to the caller?

Q4After import random, how do you roll one six-sided die?

Q5Why write common calculations as functions?

8Recap Recap

  • def defines; the function runs only when called with brackets.
  • Parameters are the inputs; return hands back the result.
  • print displays; return delivers values you can keep calculating with.
  • Import modules: math.sqrt for roots, math.pi for circles, random.randint for dice.
  • Write once, call anywhere — shorter, easier to fix, easier to test.

Other subjects in this grade

Same subject, other grades