How should my while/else be indented?



How should my while/else be indented?


When making a while / else statement, the while and the else should be on the same level of indentation. In the example code below, we can see that while and else are totally unindented:

count = 0
while count < 3:
  num = random.randint(1, 6)
  print num
  if num == 5:
    print "Sorry, you lose!"
  count += 1
  print "You win!"

If you indent the else at the end that tells the user they won, then it will attach it to the if inside of the loop, which isn’t the goal here!

FAQ: Learn Python- Loops - Your own while / else

2 posts were split to a new topic: Is there something wrong with this code?