All categories

    Files & Errors

    Reading, writing, and exception handling.

    01Write and read a file

    main.py
    with open("note.txt", "w") as f:
        f.write("hello\nworld\n")
    
    with open("note.txt") as f:
        print(f.read())
    Output
    hello
    world
    

    02Try / except

    main.py
    try:
        n = int("abc")
    except ValueError as e:
        print("Caught:", e)
    Output
    Caught: invalid literal for int() with base 10: 'abc'

    03Try / except / finally

    main.py
    try:
        x = 10 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero")
    finally:
        print("Done")
    Output
    Cannot divide by zero
    Done

    04Raise an exception

    main.py
    def sqrt(n):
        if n < 0:
            raise ValueError("n must be >= 0")
        return n ** 0.5
    
    try:
        sqrt(-1)
    except ValueError as e:
        print(e)
    Output
    n must be >= 0