Handle exceptions and validate input
Use try/except to make scripts robust against bad input.
- Validate potentially invalid input and continue safely.
Even valid Python syntax can fail at runtime due to bad input or missing data. try/except lets you handle expected failures (like invalid integer conversion) and return a clear fallback result.
1values = ["12", "oops", "5"]
2total = 0
3for value in values:
4 try:
5 total += int(value)
6 except ValueError:
7 pass
8print(total)17
Exception handling should be narrow and intentional. Catch specific exceptions when you can, and keep fallback behavior explicit so scripts remain predictable.
Key takeaways
Validate potentially invalid input and continue safely.
Read the output to check what your program did.
Keep indentation consistent in Python blocks.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Python
Write Python in the editor and run it against sample inputs. Python runs locally in your browser using a WebAssembly runtime.
Sum only valid integers
Read one line of space-separated tokens. Sum only tokens that are valid integers and print the total.
- Mixed tokens
- All invalid
Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…