🐸

The Report

Python Basicspython-architect-30-the-report
Reward: 150 XP
|

Final Phase: The Report.

The Golem is fully functional. It can read tasks, execute them safely, and recharge when needed.

Now, for the final test: The Full Simulation. The Golem must execute all tasks in its list and write a Report to a file.

The Loop

We need a method execute_all(self). It should:

  1. Open report.txt for Writing ("w").
  2. Loop through each task in self.tasks.
  3. Try to work().
  4. Write the result to the file (e.g., "Executed: Patrol\n").
  5. If it hits ValueError (Low Battery), write "Recharging...\n" and reset energy.
    def execute_all(self):
      with open("report.txt", "w") as f:
          for task in self.tasks:
              try:
                  self.work()
                  f.write(f"Done: {task}\n")
              except ValueError:
                  f.write("Recharging...\n")
                  self.energy = 20
1
Define execute_all

Create the method execute_all(self).

2
Open File

Use with open("report.txt", "w") as f: to create the report file.

3
Process Tasks

Loop through self.tasks inside the with block. Try to work(). If successful, write "Done: [task]" to file.

4
Handle & Log Errors

If logic raises ValueError, write "Recharging..." to file and recharge to 20.

This is it! You are combining Reading, Writing, Loops, Exception Handling, and OOP State Management into one system. This is Architecture.

Suggested Solution
Expand
Solution:
import random

class Golem:
  def __init__(self, name):
      self.name = name
      self.energy = 20
      self.tasks = []

  def work(self):
      loss = random.randint(5, 15)
      if self.energy < loss:
          raise ValueError("Low Battery!")
      self.energy -= loss
      # We don't print here to keep output clean, but you can if you want.

  def load_tasks(self, filename):
      with open(filename, 'r') as f:
          for line in f:
              self.tasks.append(line.strip())

  def execute_all(self):
      with open("report.txt", "w") as f:
          for task in self.tasks:
              try:
                  self.work()
                  f.write(f"Done: {task}\n")
                  print(f"Done: {task}")
              except ValueError:
                  f.write("Recharging...\n")
                  print("Recharging...")
                  self.energy = 20
                  
                  # Retry the task after recharging!
                  self.work()
                  f.write(f"Done: {task}\n")
                  print(f"Done: {task}")

bob = Golem("Bob")
bob.load_tasks("tasks.txt")
bob.execute_all()
Loading...
Terminal
Terminal
Ready to run...