Exercises: Classes and Objects Solutions

Part 1: Create a New Class

Add Properties to Robot

  1. Inside the class, define the __init__ method. It should include parameters for self, name, mass, and year.
class Robot:
   def __init__(self, name, mass, year = 1984):
      self.name = name
      self.mass = mass
      self.year = year
      self.distance = 0

Tip

Before you move on, test your new class!

main()

   test_bot = Robot()
   test_bot.name = "Rosie"
   print(test_bot.name)

Output

Rosie

Return to Exercises

Add Methods to Robot

  1. Below __init__, define a second method called move(). This method should:

    1. Only take the self parameter.

    2. Generate a random number of steps (1 - 10) for the object to take. The range should include 1 and 10 as options.

      def move(self):
         steps_taken = random.randint(1,10)
      
    3. Increase the distance property by the number of steps.

    4. Return the random number of steps.

  2. Add the __str__ method to return a string of the object properties. print(robot_name) should produce something like:

def __str__(self):
   output = "\nRobot Info: \n   Name: {0}\n   Mass: {1} kg\n   Year made: {2}\n   Distance traveled: {3}"
   return output.format(self.name, self.mass, self.year, self.distance)

Return to Exercises

Part 2: Create Objects

You now have 4 total robots. Add another statement in main() where you place the objects inside a list. Assign the collection to a variable called robots.

def main():
   bot_1 = # Your arguments here...
   bot_2 = # Your arguments here...
   bot_3 = # Your arguments here...
   bot_4 = # Your arguments here...

   robots = [bot_1, bot_2, bot_3, bot_4]

Update Distances

Use a loop to iterate through the robots list. For each object, assign a random value to the distance property, from 1000 to 3000 steps.

for robot in robots:
   robot.distance = random.randint(1000, 3000)

Return to Exercises

Part 3: Find Oldest Robot

Between the class and main(), define a function called oldest_robot. It should:

  1. Accept a list of robots as a parameter.

  2. Use a loop to iterate through the list.

  3. Return the index value for the oldest robot in the list.

    def oldest_robot(robot_list):
       robot_year = []
       for robot in robot_list:
          robot_born = robot.year
          robot_year.append(robot_born)
       oldest = robot_year.index(min(robot_year))
    
  4. If two robots have the same year value, then the one with the largest distance will be older.

    oldest_robot_year = robot_year[oldest]
    oldest_robot_distance = robot_list[oldest].distance
    same_year = robot_year.count(oldest_robot_year)
    
    if same_year > 1:
       for index in range(len(robot_list)):
          year = robot_list[index].year
    
          if year == oldest_robot_year:
             if robot_list[index].distance > oldest_robot_distance:
                oldest_robot_distance = robot_list[index].distance
                oldest = index
    

Return to Exercises

Part 4: Robot Races

Now it’s time for the robots to compete against each other! Define the robot_race function that takes a list of robots as a parameter.

Within the function:

  1. Each robot takes a turn running a race.

  2. A robot runs the race by calling its move() method several times.

  3. A robot is done with the race when it moves 30 steps or more.

  4. Create a new list to store how many turns it takes each robot to complete the race. Use the string: '____ took ____ turns to take 30 steps.' Fill in the blanks with the robot’s name and race result.

    def robot_race(robot_list):
       results = []
       for robot in robot_list:
          steps = 0
          turns = 0
       while steps <= 30:
          steps += robot.move()
          turns += 1
          results.append(f"{robot.name} took {turns} turns to take {steps} steps.")
       return results
    

Return to Exercises