Search code examples
pythontry-except

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


I am new to Python. I created a program that calculates shipping and total cost. I have it loop the user input based on user selecting y or n. I am struggling figuring out how to display a message if the user enters a negative number. I tried the if statement but the console error message displays. I want it to just display the error message I supplied. I believe I need to add a try statement?

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!")

Solution

  • Try adding a continue. With the continue statement you are going to go to the next loop iteration directly

    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!")
    

    You can also control that cost should be a number and possitive with this:

    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!")