Python_代码练习_写一个判断是否为小数的函数

这两天在学习函数,练习写一个判断是否为小数的函数,看起来蛮简单的,飞速写完很是得意,然后测了一下,发现差得好多呀,这个并不像想象那样简单,我得到的教训是,想要把一个需求哪怕再小的需求考虑周全,都不是件简单的事。

我的路还很长,但千里之行始于足下,努力学习,不断总结,持续提高,做自己喜欢做的事,享受快乐 ……

# 写一个判断是小数的函数
def is_float(s):
s = str(s)
if s.count('.') == 1:
s_left = s.split('.')[0]
s_right = s.split('.')[1]
if s_left.isdigit() and s_right.isdigit():
return True
elif s_left.startswith('-')and s_left.count('-') == 1 and s_right.isdigit():
if s_left.split('-')[1].isdigit():
return True
return False

# 下面的代码和以上相同,是加了注释的 ^_^

def is_float(s):
s = str(s) # 强制转化操作是因为传进来的被判断对象的类型具有不确定性,你需要将其统一在一个起点进行处理。
if s.count('.') == 1: # 小数的首要前提就是有且只有一个小数点。
s_left = s.split('.')[0] # 以小数点为分界点把字符串拆成左右两部分以备进一步分析。
s_right = s.split('.')[1]
if s_left.isdigit() and s_right.isdigit(): # 小数点左右都是纯的正整数,一个标准的正小数情况。
return True
elif s_left.startswith('-')and s_left.count('-') == 1 and s_right.isdigit():
# 负小数情况稍复杂,首先以负号开头,排除多个负号情况,同时小数点右侧是纯的正整数,在此情况下,
if s_left.split('-')[1].isdigit(): # 小数点左侧负号身后的部分如果是正整数字符,是个合法的负小数
return True
return False
# 除了以上正小数和负小数两种合法的情况外,其它均是不合法情况,上边的判断路线也走不进去,直接返回False结束。
# 而当符合上面的任何条件都会判断是合法小数,返回True结束程序,也走不到最后的return False这个语句。
# 所以不用看到程序最后一句是 return False 而担心。

# 以下是检测上面函数的用例,有没包含的情况吗?

print(is_float(123.456))
print(is_float(-123.456))
print(is_float(123))
print(is_float(-123))
print(is_float('123.45.6'))
print(is_float('123.4a'))
print(is_float('123a.456'))
print(is_float('-1-23.456'))
print(is_float(.456))
print(.456)  # 0.456
print(is_float(-.456))
print(-.456)  # -0.456
print(is_float('..456'))
print(is_float(--123))
print(--123) # 123 是整数
print(is_float(--.456))
print(--.456) # 0.456 是小数
print(is_float(''))
原文地址:https://www.cnblogs.com/houzhizhe/p/6957964.html