# 示例代码:判断变量类型
# 使用 type() 函数来判断变量的类型
def check_type(variable):
return type(variable)
# 示例 1: 判断整数类型
num = 10
print(f"变量 num 的类型是: {check_type(num)}") # 输出: <class 'int'>
# 示例 2: 判断字符串类型
string = "Hello, World!"
print(f"变量 string 的类型是: {check_type(string)}") # 输出: <class 'str'>
# 示例 3: 判断列表类型
list_example = [1, 2, 3]
print(f"变量 list_example 的类型是: {check_type(list_example)}") # 输出: <class 'list'>
# 示例 4: 使用 isinstance() 函数进行类型检查
def check_instance(variable, type_to_check):
return isinstance(variable, type_to_check)
# 检查是否为整数
print(f"变量 num 是否为整数: {check_instance(num, int)}") # 输出: True
# 检查是否为字符串
print(f"变量 string 是否为字符串: {check_instance(string, str)}") # 输出: True
# 检查是否为列表
print(f"变量 list_example 是否为列表: {check_instance(list_example, list)}") # 输出: True
type() 函数:用于返回变量的数据类型。例如,type(10) 返回 <class 'int'>。isinstance() 函数:用于检查一个对象是否是指定类型的实例。它比 type() 更灵活,因为它可以处理继承关系。例如,isinstance(10, int) 返回 True。通过这些方法,你可以轻松地在 Python 中判断变量的类型。
下一篇:python word
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站