I’m currently learning python using Learn Python the Hard Way and really enjoying it. In one of the lesson examples, there is a use of ‘return’ that I fail to grasp.
The lesson I’m stuck on is Exercise 43: Gothons From Planet Percal #25. I understand that when the game is first run next_room_name is set to central_corridor and so central_corridor() is called during the first loop under play().
What I don’t understand is how self.start get’s re-assigned.
For example, in the instance of death being returned under central_corridor(). After the return on line 49, we’re back in the play(self): while True loop. The first line is next_room_name = self.start As far as I know, self.start still equals central_corridor, but it apparently is now equalling death.
Does this mean that after death is returned, and still in the while loop under play(), the object Game() has been reinitialized, the __init__ being fed the results of the return? I’m confused how the next_room_name = self.start under __init__ is being reassigned to death when we’re technically still in the play(self): while True loop and haven’t exited it. I guess I’m confused as to where death is being returned to.
So let’s walk through a few steps of it up until the
whileloop:Here we instantiate
a_game, with thestart_value=central_corridor. So far, so good 🙂 Now we runa_game.play():As you correctely stated,
next_room_namegets assigned the valuecentral_corridor, and then thewhileloop begins.This may be the important part to get – the
whileloop only executes thewhilepiece and everything indented undnerneath it –next_room_nameis not reassigned toself.starteach time. Instead, we defineroomas the attributenext_room_name(which iscentral_corridor), and then run the method of the same name. The return value of that method (let’s saydeath) is then used in the next loop, meaning thatroom = death,next_room_name=the result ofdeath(), which prints a random quip and then exits. If the name were another room, it would continue the loop.