将用户输入限制在两个数字之间

时间:2018-09-17 11:32:33

标签: python python-3.x

我是python的初学者,我想将用户输入限制在两个数字之间。我该怎么办?

我想将最小值设置为0.2,将最大值设置为100,并显示订单价格。

3 个答案:

答案 0 :(得分:1)

while True:
    user_input = input("Enter a number between 0.2 and 100: ")
    if user_input.isdigit() and 0.2 <= float(user_input) <= 100:
        break
    else: 
        print("insert a number within the defined bounds!")

可以修改此方法以满足您的特定需求。首先,您定义一个while循环,该循环将一直执行到您从边界内从用户那里获得一个数字为止。然后,将user_input强制转换为float。然后,break如果它在限制范围内,如果不在限制范围内,则循环将从头开始。

关于您在评论中的问题...

while True:
    user_input = input("Enter a number between 0.2 and 100: ")
    if user_input.isdigit(): 
        if float(user_input) <= 0.2:
            print("below range")            
        elif float(user_input) >= 100:
            print("above range")
        else: 
            print("your're inside the range. well done")
            break

答案 1 :(得分:0)

这将确保用户不会因输入错误而使程序崩溃。

while True:
    user_input = input("Enter a number between 0.2 and 100: ")
    if not user_input.isdigit():
        print("Bad input!")
    elif float(user_input) < 0.02:
        print("Input too small.")
    elif float(user_input) > 100:
        print("Input too large.")
    else:
        break  # input was fine, can exit the loop

# Use user_input here

答案 2 :(得分:-1)

要限制输入范围(假设这是您想要的),您可以使用简单的while循环,例如:

userinput = float(input("How much cheese do you want? Enter a number between 0.2 and 100: "))

while ((userinput < 0.2) or (userinput > 100)):
    userinput = float(input("Value out of bounds. Enter a number between 0.2 and 100: "))

price = userinput * 0.05

print("This much cheese will cost", price)

我将价格定为每克0.05美元,但您可以将其设置为任意价格。