Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

While loop without condition?

In thevideo about Game planing in object orientating Python, there is a while loop stated without a condition. In the video it's writen like this:

while self.player.hit_points and (self.monster or self.monsters):
  print(self.player)
  self.monster_turn()
  self.player_turn()
  self.cleanup()

I haven't started my work on this game jet, so I might figure this one out later on. But could someone, please, explain the logic behind this while loop. I've allways thought that a while loop neededto include some sort of logic test. So I would want to write the first part as

 while self.player.hit_points > 0 ...

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

In the code:

while self.player.hit_points and (self.monster or self.monsters):
  print(self.player)
  self.monster_turn()
  self.player_turn()
  self.cleanup()

the condition is self.player.hit_points and (self.monster or self.monsters)

This works because of "truthiness". If an item is non-zero, or non-None or non-empty list, tuple, set, or dict, it is considered "true". So the above condition is saying "if the player's hit_points are not zero and if monster or monsters exist" then continue loop.

It means while True if there is no statement so its going to run until that condition is false "self.player.hit_points and (self.monster or self.monsters)"

That makes sense. Thank you for your help!