Отображать сообщение об ошибке при вводе отрицательного числа. Должен ли я использовать try заявление и как? - PullRequest
0 голосов
/ 07 марта 2020

Я новичок в Python. Я создал программу, которая рассчитывает доставку и общую стоимость. У меня есть l oop пользовательский ввод, основанный на выборе пользователем 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!")

1 Ответ

1 голос
/ 07 марта 2020

Попробуйте добавить продолжение. С помощью оператора continue вы переходите на go к следующей итерации l oop напрямую

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!")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...