break statement is used to get out of the loop even if the condition has not been met. Let’s take a look at the following example:
count = 6 print('The countdown is about to begin') while (count >= 0): if (count == 0): print('the end') else: print(count) if (count == 3): print('error ... abort!') break count -= 1
First we declare a variable that has the value of 6. Then we print a simple string on the screen. The
while loop starts and it is supposed to print on the screen “the end” when it gets to 0. But there is one more condition; when
count gets to 3 the loop is broken and the message “error … abort!” is printing.
The following example is an interactive loop that inputs data with
input and exits when the user enters “stop” for the name request. I created a file named
test.py and I called it in the terminal.
while True: name = input('Type your name: ') if name == 'stop': break age = int(input('Type your age: ')) if age == 0: break print('Hi', name, '-->', int(age))
The output in the terminal is:
ddn_ro@Linux:~$ python3 test.py Type your name: Dan Type your age: 0 ddn_ro@Linux:~$ python3 test.py Type your name: Dan Type your age: 40 Hi Dan --> 40 Type your name: stop ddn_ro@Linux:~$
Something good to remember is that
input returns user input as a string.