Translation Notice
This article was machine-translated using DeepSeek-R1.
- Original Version: Authored in Chinese by myself
- Accuracy Advisory: Potential discrepancies may exist between translations
- Precedence: The Chinese text shall prevail in case of ambiguity
- Feedback: Technical suggestions regarding translation quality are welcomed
Links
Want to study Python functions? see here
How to name functions? see here
Alternative ways to pass parameters? see here
I. Functions Without Parameters
Structure
|
|
Example Program
Hello world program using functions:
|
|
Program Flow
flowchat st=>start: Start: Call print_hello_world() e=>end: End get_str_call=>operation: print_hello_world() calls getHelloWorldString() return_str=>operation: getHelloWorldString() returns 'Hello World' print_hi=>inputoutput: Return to print_hello_world(), output Hello World done=>inputoutput: Return to main program, output Done st->get_str_call->return_str->print_hi->done->e
II. Functions With Parameters
Prerequisite Knowledge
Parameters: Values passed to the function, equivalent to variables within the function:
|
|
This program is equivalent to:
|
|
Structure
|
|
The parameter list uses commas to separate parameters, e.g., a, b or c (write directly if only one parameter).
Example Program
|
|
Program Flow
flowchat
st=>start: Start: Call input("What's your name?")
e=>end: End
call_greet=>operation: input returns username, call greet(<username>)
call_get_greet_str=>operation: greet calls get_greet_str(<username>)
print_hi=>inputoutput: Return to get_greet_str, output its return value
done=>inputoutput: Return to main program, output Done
st->call_greet->call_get_greet_str->print_hi->done->e
Functions Are Objects
A function is also an object.
Proof
Define two functions first:
|
|
| Item | Supported/Exists | Proof |
|---|---|---|
| Assignment | Y | c = a works; c becomes callable |
| Attributes | Y | type(a) returns class <'function'> |
| Type | Y |