When you run the code below, do you expect it to be like a Eutopian world, one with no errors?
age = input('Enter your age:')
print('You are {} next year!'.format(input + 1))
Nope. The user can input 19
but s/he can also input foo
which is not a valid age/number. Can you try to input foo
and see what happens?
Did you get also the following error?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
My two cents - Do not be terrified when your best friend, the Python interpreter, returns/raises an error. S/he is just telling you that something bad happened and you can try to help her/him to handle the error.
As a Python ninja:
- Learn how to handle exceptions.
- Learn how to ask for forgiveness but also know when to take caution first, EAFP vs LBYL.
- Know that sometimes it's okay to fail.
Rewrite the code above to handle error.
Be creative! Tip: You may just notify the user for his/her mistake or ask him/her for a new input ;)
- Pep 463: Exception-catching expressions
- Diaper Pattern also known as Pokemon Exception Handling