以下是一个示例代码,用于比较不同类型的可比较数字与零的大小:
def compare_with_zero(num):
if isinstance(num, (int, float)):
if num > 0:
return "{} is greater than zero.".format(num)
elif num < 0:
return "{} is less than zero.".format(num)
else:
return "{} is equal to zero.".format(num)
else:
return "Invalid input. Only numeric values can be compared with zero."
# 测试示例
print(compare_with_zero(10)) # 10 is greater than zero.
print(compare_with_zero(-5.5)) # -5.5 is less than zero.
print(compare_with_zero(0)) # 0 is equal to zero.
print(compare_with_zero("abc")) # Invalid input. Only numeric values can be compared with zero.
这个示例代码定义了一个函数compare_with_zero,它接受一个数字作为参数num。函数首先检查num是否为int或float类型,如果是,则通过与零进行比较来确定其大小。如果num大于零,则返回"num is greater than zero.",如果num小于零,则返回"num is less than zero.",如果num等于零,则返回"num is equal to zero."。如果num不是数字类型,则返回"Invalid input. Only numeric values can be compared with zero."。
你可以根据需要进行修改和扩展这个示例代码。