-11

Is there a use of break statement in python? I noticed that we can end the while loop with another faster ways.

As an example we can say:

name=""
while name!="Mahmoud": 
    print('Please type your name.')
    name = input()
print('Thank you!')

instead of:

while True:
    print('Please type your name.')
    name = input()
    if name == 'Mahmoud':  
        break
print('Thank you!')

and what is the meaning of while True?

dimo414
  • 47,227
  • 18
  • 148
  • 244
  • 2
    You should probably take a look at the [official Python tutorial](https://docs.python.org/3.4/tutorial). – TigerhawkT3 Sep 03 '15 at 20:36
  • While true means: while true == true...which it always does, so it is a way of creating an infinite loop. A break has many many uses...to many examples. – sw123456 Sep 03 '15 at 20:39
  • 1
    Shorter isn't always better. There are plenty of other uses of `break` than polling for input. Don't assume just because it doesn't look good to you in one case that it serves no purpose. – dimo414 Sep 03 '15 at 20:40
  • Why do you criticize me i just wanted to know what is its other uses? i didn't say it's useless :) – Mahmoud Naguib Sep 03 '15 at 20:56
  • I note that those two code blocks above are not [entirely equivalent](http://stackoverflow.com/questions/3295938/else-clause-on-python-while-statement), because Python's while loop can have an else clause. – NightShadeQueen Sep 03 '15 at 21:44

1 Answers1

3

break is useful if you want to end the loop part-way through.

while True:
  print('Please type your name.')
    name = input()
    if name == 'Mahmoud':
      break
    print('Please try again')
  print('Thank you!')

If you do this with while name != 'Mahmoud':, it will print Please try again at the end, even though you typed Mahmoud.

while True: means to loop forever (or until something inside the loop breaks you out), since the looping condition can never become false.

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
Barmar
  • 741,623
  • 53
  • 500
  • 612