输入负数时显示错误信息。我应该使用 try 语句吗?如何使用?

Display error message when negative number entered. Should I use try statement and how?

我是 Python 的新手。我创建了一个计算运费和总成本的程序。我让它根据用户选择 y 或 n 来循环用户输入。如果用户输入负数,我正在努力弄清楚如何显示消息。我尝试了 if 语句,但显示了控制台错误消息。我希望它只显示我提供的错误消息。我相信我需要添加一个 try 语句?

print ("Shipping Calculator")

answer = "y"
while answer == "y":

    cost = float(input("Cost of item ordered: "))

    if cost <0:
        print ("You must enter a positive number. Please try again.")
    elif cost < 30:
        shipping = 5.95
    elif cost > 30 and cost <= 49.99:
        shipping = 7.95
    elif cost >= 50 and cost <= 74.99:
        shipping = 9.95
    else:
        print ("Shipping is free")

    totalcost = (cost + shipping)


    print ("Shipping cost: ", shipping)
    print ("Total cost: ", totalcost)
    answer = input("\nContinue (y/n)?: ")
else:
    print ("Bye!")

尝试添加一个继续。 使用continue语句你将直接进入下一个循环迭代

print ("Shipping Calculator")

answer = "y"
while answer == "y":

    cost = float(input("Cost of item ordered: "))

    if cost <0:
        print ("You must enter a positive number. Please try again.")
        continue
    elif cost < 30:
        shipping = 5.95
    elif cost > 30 and cost <= 49.99:
        shipping = 7.95
    elif cost >= 50 and cost <= 74.99:
        shipping = 9.95
    else:
        print ("Shipping is free")

    totalcost = (cost + shipping)


    print ("Shipping cost: ", shipping)
    print ("Total cost: ", totalcost)
    answer = input("\nContinue (y/n)?: ")
else:
    print ("Bye!")

您还可以控制成本应该是一个数字并且是正数:

print ("Shipping Calculator")

answer = "y"
while answer == "y":

    cost_string = input("Cost of item ordered: ")
    if not cost_string.isdigit():
        print ("You must enter a positive number. Please try again.")
        continue
    cost = float(cost_string)

    if cost < 30:
        shipping = 5.95
    elif cost > 30 and cost <= 49.99:
        shipping = 7.95
    elif cost >= 50 and cost <= 74.99:
        shipping = 9.95
    else:
        print ("Shipping is free")

    totalcost = (cost + shipping)


    print ("Shipping cost: ", shipping)
    print ("Total cost: ", totalcost)
    answer = input("\nContinue (y/n)?: ")
else:
    print ("Bye!")