Python:针对浮点数和字符串的输入验证

时间:2018-09-25 01:11:14

标签: python string validation floating-point int

此代码接受用户输入并将其更改为整数,然后检查int是否在0到10之间。我还希望此代码针对浮点数和非数字字符串验证用户输入,并在返回时返回用户输入了错误的输入。例如:用户输入3.5或“十”并出现错误并再次循环。

 pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))

while pyramid < 0 or pyramid > 10:
    print("That value is not in the correct range. Please try again.")
    pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))

1 个答案:

答案 0 :(得分:0)

我建议尝试:

  1. 无限循环(while 1
  2. 将输入转换为浮点数,如果成功,则可以检查其是否包含小数点(pyramid % 1 != 0),并在这种情况下打印相应的错误。
  3. 将输入转换为整数,然后中断循环。
  4. 显示输入不是整数的错误
while 1:

    str_in = input("Please enter an integer between 0 and 10 to begin the sequence: ")

    try:
        pyramid = float(str_in)
        if(pyramid % 1 != 0):
            print("That value is a float not an integer. Please try again.")
            continue
    except:
        pass

    try:
        pyramid = int(str_in)
        if pyramid >= 0 and pyramid <= 10:
            break
    except:
        pass

    print("That value is a string not an integer. Please try again.")

print("Your value is {}".format(pyramid))