Phase 4: The Mission.
Our Golem is alive (__init__), active (work), and safe (if energy < loss).
But it's just wandering around randomly. We need to give it a Purpose.
We have a list of tasks in tasks.txt. We need to load them into the Golem's brain (self.tasks).
Loading Data
We will add a method load_tasks(self, filename).
It should:
- Open the file using
with. - Read all lines.
- Clean them (remove
\n) and store them inself.tasks.
def load_tasks(self, filename):
with open(filename, 'r') as f:
for line in f:
# remove spaces/newlines
clean_task = line.strip()
self.tasks.append(clean_task)
print("Tasks loaded!")
1
Initialize List
In __init__, add self.tasks = [] to create an empty list for tasks.
2
Define load_tasks
Create the method load_tasks(self, filename).
3
Read and Store
Open the file, strip each line, and append it to self.tasks.
Why a list? A list is the perfect structure for a queue of jobs. First in, first out!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
import random
class Golem:
def __init__(self, name):
self.name = name
self.energy = 20
self.tasks = [] # New brain storage
def work(self):
loss = random.randint(5, 15)
if self.energy < loss:
raise ValueError("Low Battery!")
self.energy -= loss
print(f"{self.name} works. Energy: {self.energy}")
def load_tasks(self, filename):
with open(filename, 'r') as f:
for line in f:
self.tasks.append(line.strip())
print(f"Loaded {len(self.tasks)} tasks.")
bob = Golem("Bob")
bob.load_tasks("tasks.txt")
print(bob.tasks)Loading...
Terminal
Terminal
Ready to run...