Learn Python for Data Science (Course I)July 18, 2020 2020-08-26 9:26
Learn Python for Data Science (Course I)
- Welcome to Course I!
- Installing Python and Getting Started
- Data Types and Operations in Python
- Control Flow Tools in Python
- Errors and Exceptions in Python
- Classes and Objects in Python
- Standard Libraries in Python
- Virtual Environments and Packages in Python
- Working with Files in Python
- End of Course
Errors and Exceptions in Python
In this chapter, we will learn about when and why various errors and exceptions in Python. We will also discuss different ways to handle them.
Syntax errors, also known as parsing errors, are errors where the parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected.
>>> while True print('Hello world') File "", line 1 while True print('Hello world') ^ SyntaxError: invalid syntax
Even if a statement or expression is syntactically correct, it may cause an error while executing it. Such errors detected during the program execution are termed as exceptions.
>>> 10 * (1/0) Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero
Python provides a set of statements that can be used to handle such errors and exceptions in Python. It is like try catch blocks used in other programming languages such as C, C++, and Java.
try: # Code to be executed by default except: # Code to be executed if try block fails to be executed
The try-except statement consists of two parts: Try and Except. It works as follows:
- The try part of the statement consists of a set of code to be executed.
- If no exception occurs, the except clause is skipped and execution of the try statement is finished.
- If an exception occurs in any part of the code in the try statement, the rest of the code is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
- If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
# Simple example of handling value error exception while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was not a valid number. Try again!")
OUTPUT: Please enter a number: dsa Oops! That was not a valid number. Try again! Please enter a number: 5
In this chapter, we discussed different errors and exceptions in Python. In the upcoming chapter, we will dive deeper into the concepts of Object-Oriented Programming through a lesson on Classes and Objects.