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
1
2
3
|
def <function_name>(): # Mandatory
<function_body> # Optional
return <return_value> # Optional
|
Example Program
Hello world
program using functions:
1
2
3
4
5
6
7
8
9
10
11
|
# prints 'Hello World\nDone'
# Author: GoodCoder666
def getHelloWorldString():
return 'Hello World'
def print_hello_world():
print(getHelloWorldString())
print_hello_world()
print('Done')
# Output:
# Hello World
# Done
|
Program Flow
1
2
3
4
5
6
7
8
9
|
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:
1
2
3
4
|
def param_test(a, b):
a, b = b, a
print(a, b)
param_test(5, 6) # Output: 6 5
|
This program is equivalent to:
1
2
3
4
5
6
|
def param_test():
a, b = 5, 6
#-----Same below-----#
a, b = b, a
print(a, b)
param_test() # Output: 6 5
|
Structure
1
2
3
|
def <function_name>(<parameter_list>): # Mandatory
<function_body> # Optional
return <return_value> # Optional
|
The parameter list uses commas to separate parameters, e.g., a, b
or c
(write directly if only one parameter).
Example Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# prints 'Hi, {name}!'
# Author: GoodCoder666
def get_greet_str(name):
return 'Hi, ' + name + '!'
def greet(name):
print(get_greet_str(name))
greet(input("What's your name? "))
print('Done')
# Input: GoodCoder666
# Output:
# Hi, GoodCoder666!
# Done
|
Program Flow
1
2
3
4
5
6
7
8
9
|
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:
1
2
3
4
|
def a(a, b):
return a + b
def b():
return a(1, 2)
|
Item |
Supported/Exists |
Proof |
Assignment |
Y |
c = a works; c becomes callable |
Attributes |
Y |
type(a) returns class <'function'> |
Type |
Y |
|