You must first complete Conditional Statements Part 2 before viewing this Lesson

Ending a while True loop

Introduction

We’re going to add a final touch to our Coder’s Light Switch by adding another elif condition that ends the loop without using the interrupt from Ctrl + C

Components Needed

  • Little Python Brain
  • A tablet/phone/laptop
Steps

1

The break block

Recall that a while True block repeats the code inside it indefinitely. In the case of this light switch, it will keep on asking for an input until we interrupt it by pressing Ctrl + C. 

While this is all well and good, there’s a smoother way to break out of the loop. We can do this by utilizing the break block.

2

Using the break block

To use the break block, we can make another elif condition for ending the loop.

Let’s set the condition of this to color is “end”. Remember to put it before the else block inside our loop!

3

Adding a code after the loop

To verify that we’re breaking out of the loop, we can add a print line after the whole while True block. Run it and try out all the colors!

The Complete Code

Back to: Beginner > Coder's Light Switch
© 2020 Little Python

CONTACT US

    Log in with your credentials

    or    

    Forgot your details?

    Create Account