🐸

The Heart

Python Basicspython-architect-27-the-heart
Reward: 120 XP
|

Phase 2: The Heart.

The Golem stands still. It looks perfect, but it does nothing. It's just a statue.

Life is unpredictable. To bring it to life, we need to inject a bit of Chaos (Randomness) into its core.

The work Method

We will teach the Golem to work(). But work is tiring, and sometimes it's harder than others. We'll use the random module to simulate this unpredictability.

import random

# ... inside class ...
  def work(self):
      # Lose between 5 and 15 energy
      loss = random.randint(5, 15)
      self.energy -= loss
      print(self.name + " works hard!")
1
Import Chaos

At the very top, import random.

2
Define work()

Inside the class, add a new method work(self).

3
Drain Energy

Inside work:

  1. Calculate loss = random.randint(5, 15).
  2. Subtract loss from self.energy.
  3. Print something like "... is working...".

Self-Modification: Notice how the object modifies itself (self.energy -= ...). This is the power of OOP—objects maintain their own state!

Suggested Solution
Expand
Solution:
import random

class Golem:
  def __init__(self, name):
      self.name = name
      self.energy = 100

  def work(self):
      loss = random.randint(5, 15)
      self.energy -= loss
      print(self.name + " is working hard!")

# Test drive with random
bob = Golem("Bob")
bob.work()
print(bob.energy)
Loading...
Terminal
Terminal
Ready to run...