首页 > 编程语言 > 详细

Python学习笔记--8.4 函数--校验小数类型

时间:2018-09-15 00:20:12      阅读:238      评论:0      收藏:0      [点我收藏+]

def check_float(s)

return true
    return false

1.5 1.34
-0.5 -8.4
输入这些数字,判断是否是小数。

分析:

符合正小数的条件:
1,小数点个数为1。‘1.5‘ count(‘.‘),但是不能判断a.3.
2,小数点左边和右边都是整数。

符合负小数的条件:
1,小数点个数为1。
2,小数点左边和右边都是整数。
3,负号开头,并且只有一个负号。-----1.3

 def check_float(s):
#     这个函数的作用就是判断传入的字符串是否是合法小数
#     :param s: 传入一个字符串
#     :return: true/false

     s=str(s)#输入的内容强制转成字符串。
     if s.count(‘.‘)==1:
         s_split=s.split(‘.‘)#根据.分割字符串
         #1.5 [1,5]
         left,right=s_split
         # left=s_split[0]
         # right=s_split[0]
         if left.isdigit()and right.isdigit():
             return True
         elif left.startswith(‘-‘)and left[1:].isdigit()and right.isdigit():  #1234.5 [‘-123‘,‘5‘] #数字以负号开头,并且,下标为1开始到结尾的内容为数字,并且小数点右侧是数字。
             return True
     return False

 print(check_float(1.3))
 print(check_float(-1.3))
 print(check_float(‘01.3‘))
 print(check_float(‘1.3‘))
 print(check_float(‘-1.3‘))
 print(check_float(‘-a.3‘))
 print(check_float(‘a.3‘))
 print(check_float(‘---1.3‘))

# 打印结果:
# True
# True
# True
# True
# True
# False
# False
# False

 

Python学习笔记--8.4 函数--校验小数类型

原文:https://www.cnblogs.com/youyou-luming/p/9649520.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!