Skip to content

Errors, Files and OOP

>Errors, Files and OOP — cheat sheet

Handle problems safely, save text, and use classes to group related data and behavior.

Exceptions

try:
    result = 8 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
Put code that might fail inside try.
try:
    number = int("cat")
except ValueError:
    number = 0
Catch the specific error you expect.
try:
    result = 8 / 2
except ZeroDivisionError:
    result = 0
else:
    print(result)
else runs only when the try block succeeds.
class TooYoungError(Exception):
    pass
Create a custom exception by inheriting from Exception.

Raise and finish safely

if age < 18:
    raise ValueError("Must be 18 or older")
raise stops with an error your program should not accept.
try:
    print("Work")
finally:
    print("Finished")
finally runs whether an error happens or not.
try:
    int("cat")
except ValueError as error:
    print(error)
Store an exception message in a name when useful.
scores = {}
try:
    print(scores["Sam"])
except KeyError:
    print("Missing score")
A missing dictionary key raises KeyError.

Files

with open("demo.txt", "w", encoding="utf-8") as file:
    file.write("First line\n")
w writes a file and replaces old contents.
with open("demo.txt", "r", encoding="utf-8") as file:
    contents = file.read()
read returns the whole file as one string.
with open("demo.txt", "a", encoding="utf-8") as file:
    file.write("Another line\n")
a adds text at the end without replacing it.
with open("demo.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())
Loop over a file to handle one line at a time.

Classes and objects

class Dog:
    def __init__(self, name):
        self.name = name
__init__ sets up a new object.
pet = Dog("Milo")
print(pet.name)
Create an object from a class and read its attribute.
class Student:
    school = "PyQuest Academy"
A class attribute is shared by objects of that class.
class Book:
    def __str__(self):
        return "A book"
__str__ gives print a readable description.

Inheritance and generators

class Dog(Animal):
    pass
A child class can reuse a parent class.
class Dog(Animal):
    def speak(self):
        return "Woof"
Override a parent method with child behavior.
color_iterator = iter(["red", "blue"])
print(next(color_iterator))
iter creates an iterator and next gets one value.
def countdown(start):
    while start > 0:
        yield start
        start -= 1
yield makes a generator that produces values on demand.
All cheat sheets