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
ValueErrorhappens anywhere in there, it jumps straight toexcept ValueErrorinstead of crashing. - If nothing goes wrong, the
exceptpart 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.
- Ask
How many slices?withinput() - If it's not a number, print
That's not a number!and ask again - 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.