• 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(''))
  • 相关阅读:
    C++中类模板的概念和意义
    C++中模板类声明和实现能否分离?
    C/C++ 关于大小端模式,大小端字节序转换程序
    C++中的赋值操作符重载和拷贝构造函数
    C++中的友元
    C/C++内存对齐详解
    C++ 虚函数表、函数地址、内存布局解析
    虚析构函数的必要性(C++)
    C++中的抽象类和接口
    C++中的单例类模板
  • 原文地址:https://www.cnblogs.com/victory-0315/p/8617418.html
Copyright © 2020-2023  润新知