DEV Community

Cover image for 🎁Learn Python in 10 Days: Day8
William
William

Posted on

🎁Learn Python in 10 Days: Day8

Today, we're continuing our 10-day journey to learn Python, kicking off Day 8's lesson. If you haven't checked out Day 1 yet, you can find it here: 🎁Learn Python in 10 Days: Day 1

Day 8: Exceptions

1. Understanding Exceptions

When the Python interpreter detects an error, it can't execute the code and instead displays an error message. This is called an "exception," or more commonly, a "bug."

Historically, a literal bug (insect) caused a malfunction in a computer, so we now refer to software errors as "bugs."

Example: Trying to open a non-existent file.

f = open("www.txt", "r", encoding="utf-8")
# FileNotFoundError: [Errno 2] No such file or directory: 'www.txt'
Enter fullscreen mode Exit fullscreen mode

2. Handling Exceptions

Handling exceptions means preparing for and dealing with potential errors to avoid program crashes.

Reasons to catch exceptions:

  1. Improve Stability: Prevent your program from crashing due to errors.
  2. Easier Debugging: Get detailed error info to quickly locate issues.
  3. Better Maintenance: Separate error-handling code from business logic.

When encountering a bug, you can either:

  1. Stop the entire program,
  2. Handle the bug and continue running.

In practice, it's better to handle errors so that your program can continue running smoothly.

Basic syntax for catching exceptions:

try:
    # Code that may raise an error
except:
    # Code to run if an error occurs
Enter fullscreen mode Exit fullscreen mode

Example: Try opening a file in read mode, if it doesn't exist, open it in write mode.

try:
    f = open("www.txt", "r", encoding="utf-8")
except:
    f = open("www.txt", "w", encoding="utf-8")
Enter fullscreen mode Exit fullscreen mode

Catching specific exceptions:

try:
    print(name)
except NameError as e:
    print("NameError: 'name' is not defined")
Enter fullscreen mode Exit fullscreen mode

Important Notes:

  1. If the error type doesn't match the one you're catching, the exception won't be caught.
  2. Generally, put only one line of code in the try block.

Catching multiple exceptions:

try:
    print(1 / 0)
except (NameError, ZeroDivisionError):
    print("Error occurred")
Enter fullscreen mode Exit fullscreen mode

Catching all exceptions:

try:
    # Code that may raise an error
except Exception as e:
    # Code to run if any error occurs
Enter fullscreen mode Exit fullscreen mode

Using else: Code that runs if no exceptions occur.

try:
    print(1)
except Exception as e:
    print(e)
else:
    print("No exceptions occurred")
Enter fullscreen mode Exit fullscreen mode

Using finally: Code that runs no matter what.

try:
    f = open("test.txt", "r", encoding="utf-8")
except Exception as e:
    print(e)
    f = open("test.txt", "w", encoding="utf-8")
else:
    print("No exceptions occurred")
finally:
    f.close()
Enter fullscreen mode Exit fullscreen mode

3. Exception Propagation

def func1():
    print("Start of func1")
    print(1 / 0)
    print("End of func1")

def func2():
    print("Start of func2")
    func1()
    print("End of func2")

def main():
    try:
        func2()
    except Exception as e:
        print(e)

main()
# Output:
# Start of func2
# Start of func1
# division by zero
Enter fullscreen mode Exit fullscreen mode

If an exception isn't caught within a function, it propagates to the calling function.

4. Python Modules

A Python module is a file ending in .py. It can define functions, classes, and variables, and can also include executable code.

Modules help bundle related functions and data. For instance, use the time module for time-related tasks.

Importing modules:

import time

print("Start")
time.sleep(1)
print("End")
Enter fullscreen mode Exit fullscreen mode

Using from to import specific attributes:

from time import sleep

print("Start")
sleep(1)
print("End")
Enter fullscreen mode Exit fullscreen mode

Using * to import all attributes:

from time import *
sleep(1)
Enter fullscreen mode Exit fullscreen mode

Using as to create aliases:

import time as t
t.sleep(2)
print("haha")

from time import sleep as sl
sl(2)
print("hehe")
Enter fullscreen mode Exit fullscreen mode

4.2 Creating Custom Modules

You can create your own modules for specific tasks by writing Python files.

Example: Create my_module.py with a function:

# my_module.py
def my_test(a, b):
    print(a + b)

if __name__ == '__main__':
    my_test(1, 2)
Enter fullscreen mode Exit fullscreen mode
# another_module.py
from my_module import my_test
my_test(1, 2)
Enter fullscreen mode Exit fullscreen mode

5. Python Packages

A package is a collection of modules. Physically, it's a folder containing a special __init__.py file.

Creating a package:

  1. Create a folder named my_package.
  2. Add modules (my_module1.py, my_module2.py).
  3. Add an __init__.py file.

Using packages:

import my_package.my_module1
my_package.my_module1.my_function()
Enter fullscreen mode Exit fullscreen mode

Or using from import:

from my_package import my_module1
my_module1.my_function()
Enter fullscreen mode Exit fullscreen mode

5.2 Installing Third-Party Packages

Use pip to install third-party packages:

pip install package_name
Enter fullscreen mode Exit fullscreen mode

To speed up the process by using a mirror site:

pip install -i https://packagecloud.io/pypa/python/simple package_name
Enter fullscreen mode Exit fullscreen mode

Example: Creating a custom package my_utils.

  1. Create a folder my_utils.
  2. Add str_util.py and file_util.py.
# str_util.py
def str_reverse(s):
    return s[::-1]

def substr(s, x, y):
    return s[s.index(x):s.index(y)]

# file_util.py
def print_file_info(file_name):
    try:
        with open(file_name, 'r') as f:
            content = f.read()
            print(content)
    except Exception as e:
        print(e)

def append_file_info(file_name, data):
    with open(file_name, 'a') as f:
        f.write(data + "\n")
Enter fullscreen mode Exit fullscreen mode

Then use these modules in your scripts:

from my_utils import str_util, file_util

print(str_util.str_reverse("hello"))
file_util.append_file_info("test.txt", "Some data")
Enter fullscreen mode Exit fullscreen mode

By following these guidelines, you can effectively handle exceptions, organize your code with modules and packages, and utilize third-party libraries to enhance your Python projects.

Top comments (0)