【问题标题】:How to determine input as a floating point number and/or integer within a loop? [duplicate]如何在循环中将输入确定为浮点数和/或整数? [复制]
【发布时间】:2016-06-29 06:40:21
【问题描述】:

如何确定用户输入是循环内的float 还是integer?如果他们输入的不是integer/float,我希望循环重复,直到他们正确输入float/integer

感谢任何帮助! :)

【问题讨论】:

标签: python loops floating-point integer


【解决方案1】:

您可以在尝试使用 float() 和 int() 函数解析不正确的数据时使用正在报告的错误。首先,定义一个通用函数来解析 int 和 float 并在所有其他情况下抛出一些异常:

def parse(x):
    value=0
    try:
        value = int(x)
    except ValueError:
        try:
            value = float(x)
        except ValueError:
            raise Exception
    return value

您可以使用此通用函数来确定循环中的正确或错误输入

correct = False
while not correct:
    try:
        parse(input("Enter data:"))
        correct = True
    except Exception:
        print("Invalid input...enter again!")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多