Python Practice › Exception Handling Programs › Program 16
Ask until the input is valid
Write a Python program that keeps asking for a number until a valid one is entered.
Input
"ten", "-4", "12"
Output
Quantity: ten Please type a whole number Quantity: -4 Quantity must be positive Quantity: 12 Ordered 12
Approach
- Loop with
while True,continueon bad input andbreakon good input.
Solution
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.