Peter N
Peter N

Reputation: 31

Only accept integer (1 to 10) in user input (and give error if something else is written)

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

Upvotes: 0

Views: 951

Answers (1)

Alain T.
Alain T.

Reputation: 42133

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) 

Upvotes: 2

Related Questions