1

I have a loop in the form as below. I want to break and come out of the entire while loop if p>len(number). Number is a list here containing some numbers. The below code is not breaking from the entire loop when p is more than the len(number). Can some one help with an implementation in python.

while number[p]<0 :
  if "some condition":
    #do something
    p=p+1
    if p>len(number):
        break;
  else:
    #do something
    p=p+1
    if p>len(number)
        break;
scharette
  • 9,437
  • 8
  • 33
  • 67
Bineeta Saikia
  • 99
  • 1
  • 1
  • 6
  • 3
    Possible duplicate of [Break the nested (double) loop in Python](https://stackoverflow.com/questions/2597104/break-the-nested-double-loop-in-python) – Chris_Rands Jul 25 '18 at 13:40
  • Possible duplicate of [How to break out of multiple loops in Python?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python) – i alarmed alien Jul 25 '18 at 13:41
  • 4
    ...except there aren't actually nested loops here. `if` statements don't count, do they? – glibdud Jul 25 '18 at 13:42
  • Put the loop in a function and `return`? – Peter Wood Jul 25 '18 at 13:43
  • 1
    if you're repeating the same code in the `if` and `else` statements, it's a sign that that code doesn't need to be in the `if`/`else` statements. – i alarmed alien Jul 25 '18 at 13:45
  • The issue is, when p is greater than len(number) the list, it cannot find anything in while loop and so throws an error saying index out of range, hence I need to get out of the while loop the moment p is greater than len(number) – Bineeta Saikia Jul 25 '18 at 13:48
  • add that as a condition for your `while` loop, then -- `while p <= len(number) and number[p] < 0` – i alarmed alien Jul 25 '18 at 13:50

3 Answers3

1

Please, refer to below two links :

  1. PEP 3136 -- Labeled break and continue : https://www.python.org/dev/peps/pep-3136/
  2. Rejection of PEP 3136 -- https://mail.python.org/pipermail/python-3000/2007-July/008663.html

Hope it will help..

Shraddha
  • 791
  • 7
  • 13
1

If you want your code not to run if p is greater than len(number), add it to the conditions for the while loop:

while p <= len(number) and number[p] < 0:
  if "some condition":
    #do something
  else:
    #do something
  p=p+1

There's no need to have the same code repeated in both parts of the if/else -- just move it out so it's directly under the while.

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
1

This should be a for loop:

for value in number:
    if condition:
        do_something()
    else:
        do_other()
Peter Wood
  • 23,859
  • 5
  • 60
  • 99