Python functions and modules
Advanceddef 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.
- 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.
文體小知識:編程教學課每個概念都配一段可以親手試的代碼例子,照住輸入、改一改,最快學會。
§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
A named, reusable block of code that takes inputs and may return a result.
The Python keyword for defining a function: def name(parameters):.
The variable in the brackets at definition time — the function's input, e.g. name in def greet(name).
The actual value supplied at call time, e.g. "Mary" in greet("Mary").
The result a function hands back with return, ready for further use.
Running a function by name with brackets and arguments, e.g. greet("Mary").
A pre-written library such as math or random, available after importing.
The keyword that loads a module, e.g. import math before using math.sqrt.
Returns a random integer including both ends, e.g. random.randint(1, 6) rolls a die.
3Step by step Steps
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
5Worked example Example
Example: write a function max2(a, b) that returns the larger of two numbers, then use it on 17 and 9.
- def max2(a, b): — define with two parameters, a and b.
- Body: if a > b: return a, otherwise return b.
- Call: print(max2(17, 9)) — since 17 > 9 holds, it returns a = 17.
- Try the edge: print(max2(9, 9)) — a > b fails, so return b = 9; for equal numbers the result is still 9, correct.
- Answer: def max2(a, b): if a > b: return a, else return b; max2(17, 9) = 17.
6Common mistakes Mistakes
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.