Article Directory
link
Want to study Python
functions? See here.
How is the function named? Look here.
How can a function with parameters pass parameters? look here
One, no parameter function
structure
def <函数名>(): # 强制要求
<函数体> # 可省略
return <返回值> # 可省略
Program example
Hello world
Program with function :
# prints 'Hello World\nDone'
# Author: GoodCoder666
def getHelloWorldString():
return 'Hello World'
def print_hello_world():
print(getHelloWorldString())
print_hello_world()
print('Done')
# 输出:
# Hello World
# Done
Procedure flow chart
Second, a function with parameters
Supplementary knowledge
Parameter ( parameter ): The value given to the function, which is equivalent to a variable in the function:
def param_test(a, b):
a, b = b, a
print(a, b)
param_test(5, 6) # 输出:6 5
The above procedure is equivalent to:
def param_test():
a, b = 5, 6
#-----以下部分相同-----#
a, b = b, a
print(a, b)
param_test() # 输出:6 5
structure
def <函数名>(<参数列表>): # 强制要求
<函数体> # 可省略
return <返回值> # 可省略
Among them, the parameters in the parameter list are ,
separated by, for example a, b
, c
(If there is only one parameter, write directly)
Program example
# 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')
# 输入: GoodCoder666
# 输出
# Hi, GoodCoder666!
# Done
Procedure flow chart
Functions are also objects
A function is also an object.
prove
First define two functions:
def a(a, b):
return a + b
def b():
return a(1, 2)
project | Support/exist | prove |
---|---|---|
Assignment | AND | c = a Executable; c can be called after execution |
Attributes | AND | Execute type(a) , returnclass <'function'> |
Types of | AND |