Ask until the input is valid

EasyException Handling Programs · 16 of 20

Write a Python program that keeps asking for a number until a valid one is entered.

Advertisement
Input
"ten", "-4", "12"
Output
Quantity: ten
Please type a whole number
Quantity: -4
Quantity must be positive
Quantity: 12
Ordered 12

Approach

  1. Loop with while True, continue on bad input and break on good input.

Solution

Python
while True:    text = input("Quantity: ")    try:        qty = int(text)    except ValueError:        print("Please type a whole number")        continue    if qty <= 0:        print("Quantity must be positive")        continue    breakprint("Ordered", qty)
Outputtyped input: ten, -4, 12
Quantity: ten
Please type a whole number
Quantity: -4
Quantity must be positive
Quantity: 12
Ordered 12

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment