How should my while/else be indented?


#1

Question

How should my while/else be indented?

Answer

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!"
    break
  count += 1
else:
  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

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