Embercode
✕
Object-Oriented ProgrammingQuick quiz

Invariants

6 questions. Covers Invariants and validation in Python classes.

Questions 1 to 5 of 6

  1. 1. This set_target method should refuse any value outside 5 to 35. What goes wrong? ``python def set_target(self, target): self._target = target if target < 5 or target > 35: raise ValueError(f"target must be 5 to 35, got {target}") ``
  2. 2. Course.enrol is called for a course that is already full. Which exception should it raise?
  3. 3. What is the last line printed? ``python class Person: def __init__(self, name, age): self.name = name.strip() self.set_age(age) def set_age(self, age): if age < 0 or age > 150: raise ValueError(f"age must be between 0 and 150, got {age}") self._age = age def __str__(self): return f"{self.name} ({self._age})" asha = Person(" Asha ", 30) try: asha.set_age(200) except ValueError as err: print("rejected:", err) print("still valid:", asha) ``
  4. 4. Which built-in exception does Python raise for a value of the right kind that is not acceptable, such as an age of minus 1?

    Type your answer.

  5. 5. What is the last line printed? ``python class Course: def __init__(self, title, capacity): self._title = title self._capacity = capacity self._students = [] def enrol(self, student): if len(self._students) >= self._capacity: raise RuntimeError(f"{self._title} is full ({self._capacity} seats)") self._students.append(student) @property def capacity(self): return self._capacity @capacity.setter def capacity(self, new_capacity): if new_capacity < len(self._students): raise ValueError( f"capacity {new_capacity} is below the {len(self._students)} students already enrolled") self._capacity = new_capacity def __str__(self): return f"{self._title}: {len(self._students)}/{self._capacity}" java = Course("Java basics", 2) java.enrol("Asha") java.enrol("Ravi") try: java.capacity = 1 except ValueError as err: print("rejected:", err) print(java) ``

5 question(s) left on this page.

Typed answers ignore extra spaces and, for most questions, capital letters.