Learn Python · lesson 18 of 60 · about 8 minutes
continue and Input Checks
Ask Sam how many tasks there are today, and keep asking until the answer makes sense: skip a bad try with continue, stop with break.
What you'll learn
- Skip an iteration with continue
- Validate input in a loop
- Use while True with break
Three, 3 or 30?
Next, the assistant asks how many tasks Sam has today. People type three, 2 or 30, and int("three") stops the whole script with ValueError: invalid literal for int() with base 10: 'three'. Instead of crashing, the assistant should say what's wrong and ask again until the answer is sensible.
Skipping with continue
continue skips the rest of the current time round the loop and jumps back to the condition. The loop keeps going; only this pass is skipped.
Skip the odd numbers
n = 0
while n < 6:
n += 1
if n % 2 == 1:
continue
print(n)Output
2
4
6Asking until the answer is valid
People type unexpected things. A common pattern is while True: that keeps asking, and break once the answer is acceptable.
isdigit() is a string method that tells you whether the text is all digits, so you can check before calling int().
Keep asking for a number
while True:
reply = input("Pick 1-3: ")
if reply.isdigit() and 1 <= int(reply) <= 3:
break
print("Try again.")
print(f"You picked {reply}")Output
Pick 1-3: Try again.
Pick 1-3: Try again.
Pick 1-3: You picked 2The assistant asks until it gets a sensible number
while True:
answer = input("Tasks today? ").strip()
if not answer.isdigit():
print("Please type a whole number")
continue
tasks = int(answer)
if tasks > 5:
print("Five is plenty for one day")
continue
break
print(f"Planning {tasks} tasks")
Output
Tasks today? Please type a whole number
Tasks today? Five is plenty for one day
Tasks today? Planning 2 tasksTip
Each check that fails says what's wrong and uses continue to ask again. Only an answer that passes every check reaches the break.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.