Module 5
>Errors, Files and OOP
Handle problems safely, save data in files, and organize programs with classes.
// Lessons
5
// Quiz questions
50
// Reading time
51 min
// Exam length
15 Q
// Coding exercises
9
- 1Errors and ExceptionsYou will handle errors safely and create your own exception type. 10 min 10 questions
- 2File HandlingYou will write, read, append, and loop through text files safely. 10 min 10 questions
- 3Classes and ObjectsYou will create classes, objects, attributes, methods, and useful string output. 11 min 10 questions
- 4Inheritance and PolymorphismYou will reuse parent class code and call matching methods on different objects. 10 min 10 questions
- 5Iterators, Generators and Next StepsYou will get values one at a time with iterators and generators, then plan your next practice. 10 min 10 questions
Coding practice: write it yourself
Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (0/4 passed this visit)
You can run every exercise now. Create a free ID to keep passes, code attempts and XP.
Lab 1: Divide without crashing
Not passed yetDivide 900 by people = 0 inside try/except so that instead of a crash it prints People must be more than zero.
total = 900 people = 0 # try the division, catch ZeroDivisionError
Lab 2: Parse a number safely
Not passed yetThe text "abc" should become a number. Convert it inside try/except ValueError; on failure print not a number.
text = "abc" # int(text) will raise — handle it
Lab 3: A Dog class
Not passed yetCreate class Dog whose __init__ takes name, with method bark() returning ". Print Dog("Rex").bark().
class Dog:
def __init__(self, name):
# store name
def bark(self):
# return the sentence
print(Dog("Rex").bark())
Lab 4: Inherit and override
Not passed yetAnimal.speak() returns "...". Make Cat(Animal) override it to return "Meow", then print Cat().speak().
class Animal:
def speak(self):
return "..."
class Cat(Animal):
# override speak
print(Cat().speak())
References & Further Reading
Related entries from PyLabs's own reference library.
- open() (Open a file so you can read from it or write to it.)
- isinstance() (Check whether a value is an instance of a type.)
- iter() (Return an iterator for a collection or other iterable.)