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

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

 

posted on 2018-09-14 23:33  爱吃爱吃桃子  阅读(216)  评论(0编辑  收藏  举报