0

How can i secure that error will be presented if answer is something else than 1 to 10 in the first input "nr of cost items to be added" is written? (and promt should go back to "nr of cost items to be added").

message_error = "Not correct input."

num = int(input("Nr of cost items to be added: ") or "3")

for n in range(num):

    while True:
        try:
            cost_items = int(input("Cost per item: "))
            break
        except ValueError:
            print(message_error)  
            continue

1 Answer 1

2

Given that you have a small number of valid responses, you could check the input string against a set of valid string responses and only convert it to int once the input is one of the expected values:

while True:
    cost_item = input("Cost per item: ")
    if cost_item in map(str,range(1,11)):
        cost_item = int(cost_item)
        break
    print(message_error)

Alternatively, you could modify the loop you already have so that it only exits when the number is in the expected range and gives the error messages for both an out-of-range and an invalid number:

while True:
    try:
        cost_items = int(input("Cost per item: "))
        if cost_items in range(1,11): break
    except ValueError: pass
    print(message_error) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.