Skip to main content

Unit 4 · Loop-de-Loop · Lesson 37 of 57

Try, Try Again

Try, try again

You've been trusting your users to type numbers when you ask for numbers. That was a mistake.

age = int(input("How old are you? "))

Type sixteen into that, and:

ValueError: invalid literal for int() with base 10: 'sixteen'

int() has no idea how to turn sixteen into a number, so the whole program crashes. Users WILL type stuff like that. (Especially Alex. On purpose.)

try and except

You can tell Python: "try this, and if it blows up, do this instead."

try:
    age = int(input("How old are you? "))
    print(f"You're {age}!")
except ValueError:
    print("That's not a number!")
  • Python runs the code under try.
  • If a ValueError happens anywhere in there, it jumps straight to except ValueError instead of crashing.
  • If nothing goes wrong, the except part gets skipped.

Asking until they get it right

Put it in a loop, and you can keep asking until they give you a real number:

while True:
    try:
        age = int(input("How old are you? "))
        break
    except ValueError:
        print("That's not a number!")

print(f"Got it! You're {age}.")

while True loops forever on purpose. The only way out is the break, and Python only reaches it if int() worked.

Remember the pizza? Let's ask how many slices to order, and keep asking until we get a real number.

  1. Ask How many slices? with input()
  2. If it's not a number, print That's not a number! and ask again
  3. Once it is, print Ordering [slices] slices!

If someone types a lot, then 17, it should print:

That's not a number!
Ordering 17 slices!

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.