【问题标题】:How to print the input as an integer, float or string in Python如何在 Python 中将输入打印为整数、浮点数或字符串
【发布时间】:2021-07-29 14:46:30
【问题描述】:

我的代码的目的是让输出给出输入的数字和类型。例如:

如果输入是:10

输出应该是:10 is an integer

如果输入是:10.0

输出应该是:10.0 is a float

如果输入是:Ten

输出应该是:Ten is a string

我是一个编程初学者,所以我还不知道任何“高级”功能。我也不应该使用它,因为这是一个开始的学校作业。通常我应该能够使用 if、elif 和 else 语句以及一些 int ()float ()type () 函数来解决这个问题。

x = input("Enter a number: ")

if type(int(x)) == int:
    print( x, " is an integer")
elif type(float(x)) == float:
    print( x, "is a float")
else:
    print(x, "is a string")

但是,我一直卡住,因为输入总是作为字符串给出。所以我认为只有当我把它放在 if、elif、else 语句中时,我才应该将它转换为整数/浮点数,然后逻辑上会出现错误。有谁知道我该如何解决这个问题?

【问题讨论】:

标签: python if-statement input


【解决方案1】:

记住Easy to ask forgiveness than to ask for permission (EAFP)

你可以使用try/except:

x = input("Enter a number: ")
try:
    _ = float(x)
    try:
        _ = int(x)
        print(f'{x} is integer')
    except ValueError:
        print(f'{x} is float')
except ValueError:
    print(f'{x} is string')

样品运行

x = input("Enter a number: ")
Enter a number: >? 10
10 is ineger

x = input("Enter a number: ")
Enter a number: >? 10.0
10.0 is float

x = input("Enter a number: ")
Enter a number: >? Ten
Ten is string

【讨论】:

    【解决方案2】:

    你可以使用:

    def get_type(x):
        ' Detects type '
        if x.isnumeric():
            return int      # only digits
        elif x.replace('.', '', 1).isnumeric():
            return float    # single decimal
        else:
            return None
    
    # Using get_type in OP code
    x = input("Enter a number: ")
    
    x_type = get_type(x)
    if x_type == int:
        print( x, " is an integer")
    elif x_type == float:
        print( x, "is a float")
    else:
        print(x, "is a string")
    

    示例运行

    Enter a number: 10
    10  is an integer
    
    Enter a number: 10.
    10. is a float
    
    Enter a number: 10.5.3
    10.5.3 is a string
    

    【讨论】:

      【解决方案3】:

      因为它总是一个字符串,你可以做的是检查字符串的格式:

      案例 1:所有字符都是数字(它是 int)

      案例 2:所有数字字符,但只有一个 '.'介于两者之间(这是一个浮动)

      其他一切:它是一个字符串

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-21
        • 1970-01-01
        • 1970-01-01
        • 2015-01-18
        • 2016-02-06
        • 1970-01-01
        相关资源
        最近更新 更多