博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python_代码练习_写一个判断是否为小数的函数
阅读量:4484 次
发布时间:2019-06-08

本文共 1698 字,大约阅读时间需要 5 分钟。

# 写一个判断是小数的函数 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/victory-0315/p/8617418.html

你可能感兴趣的文章
MySql可视化工具MySQL Workbench使用教程
查看>>
个人站立会议第二阶段07
查看>>
云时代架构阅读笔记五——Web应用安全
查看>>
IOS 单击手势和cell点击冲突
查看>>
学习_HTML5_day3
查看>>
计算机网络与应用第二次笔记
查看>>
Django之ORM查询
查看>>
学习python第七天
查看>>
Flask基础(07)-->正则自定义转换器
查看>>
C++著名程序库的比较和学习经验(STL.Boost.GUI.XML.网络等等)
查看>>
Spring Boot构建RESTful API与单元测试
查看>>
【JavaScript你需要知道的基础知识~】
查看>>
谷歌搜索语法
查看>>
static 静态变量
查看>>
Docker 安装及问题处理
查看>>
匿名内部类
查看>>
BZOJ4071: [APIO2015]八邻旁之桥
查看>>
Redis的六种特性 场景
查看>>
mysql 添加[取消]timestamp的自动更新
查看>>
码农的半衰期只有15年?
查看>>