1. The return value of the function None
1. Empty return value
In Python functions, the return return value is optional, and the function can have no return value;
def 函数名(函数参数):
"""函数文档字符串(可选)"""
# 函数体
# return 返回值 (可选)
If the return value is not defined in the Python function, then the special literal value None is returned, and its type is <class 'NoneType'> ;
None means that it has no practical meaning, returns empty, and does not need to process the return value information;
Returning None in Python is equivalent to
- void in Java/C/C++
- Units in Kotlin
etc void return value;
2. Code example - receive None return value
In the following code, the hello function does not use the return keyword to return the return value;
The hello function does not display a defined return value, in fact, the function returns a None return value;
Use a variable to receive the return value of the function, the return value is None, and the return value type is NoneType;
Code example:
"""
接收 函数 None 返回值示例
"""
# 定义无返回值的函数
def hello():
print("Hello World")
# 获取函数的空返回值
result = hello()
# 打印返回值
print(result) # 输出 None
# 打印返回值类型
print(type(result)) # 输出 <class 'NoneType'>
Results of the :
Hello World
None
<class 'NoneType'>
3. Code example - use the return keyword to return None
In this example, there are more return None return values than the previous example, and its execution effect is exactly the same as no return value;
Code example:
"""
接收 函数 None 返回值示例
"""
# 定义无返回值的函数
def hello():
print("Hello World")
return None
# 获取函数的空返回值
result = hello()
# 打印返回值
print(result) # 输出 None
# 打印返回值类型
print(type(result)) # 输出 <class 'NoneType'>
Results of the :
Hello World
None
<class 'NoneType'>
2. Application scenario of None value
1. Brief introduction of None value application scenarios
Application scenario of function None return value:
- Function return value: indicates that the function has no return value;
- For if judgment: None is equivalent to the Boolean value False;
- Define a variable with no initial content: if you do not need a specific value for the variable when defining the variable, you can temporarily assign None to it;
2. Code example - use None for if judgment
Code example:
"""
使用 None 作为 if 判定条件 代码示例
"""
# 定义函数 返回 None 返回值
def is_adult(age):
if age > 18:
return "adult"
else:
return None
# 接收返回值
result = is_adult(12)
# 使用返回值进行判定
if not result:
print("未成年")
else:
print("成年")
Results of the :
未成年
3. Code example - define a variable without initial content
Code example:
"""
使用 None 定义无初始内容变量 代码示例
"""
# 定义无初始内容变量
name = None
print(name)
# 为 name 设置真实值
name = "Tom"
print(name)
Results of the :
None
Tom