Catching bad input
text = input("Enter a number: ") try: n = int(text) print("Double is", n * 2) except ValueError: print(text, "is not a whole number")
Uses the input abc
Write Python. Understand every error.
Python basics · topic 16 of 25
When Python meets a problem it cannot handle, it raises an exception and the program stops. The explanation panel in this app tells you what each one means. Common ones are ValueError, ZeroDivisionError, IndexError, KeyError and TypeError.
You can catch an exception with try and except. Python runs the try block; if a matching error happens, it jumps to the except block instead of stopping.
try: n = int(input()) print(100 / n) except ValueError: print("Please type a number") except ZeroDivisionError: print("Cannot divide by zero")
Name the specific exception you expect. A bare except: catches everything, including mistakes you would rather see and fix.
try: holds the code that might failexcept SomeError: handles that errorelse: runs only if no error happenedfinally: always runs, error or nottry block holds code that might fail, and except SomeError: handles that specific error.else runs only if nothing went wrong, and finally always runs.ValueError, instead of everything, so real bugs are not hidden.except:, which hides mistakes you should see.except ValueError does not catch a division by zero. Read the ZeroDivisionError guide.try, so it is unclear what actually failed. Open the error guide.
text = input("Enter a number: ") try: n = int(text) print("Double is", n * 2) except ValueError: print(text, "is not a whole number")
Uses the input abc
nums = [10, 20, 30] try: i = int(input()) print(nums[i]) except ValueError: print("Not a number") except IndexError: print("No item at that position")
Uses the input 5
try: x = 10 / 2 except ZeroDivisionError: print("error") else: print("result", x) finally: print("finished")
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
print(10 / 0) cause?Dividing by zero raises ZeroDivisionError.
int("abc") cause?The type is right (a string) but its value cannot become a number, so it is a ValueError.
try: x = int("7a") except ValueError: x = -1 print(x)
int("7a") fails, so the except block sets x to -1.
try: print("A") y = 1 / 0 print("B") except ZeroDivisionError: print("C")
The error happens before "B" is printed, so Python jumps to except.
A position past the end of a list raises IndexError.