Exit while loop in Python

前端 未结 6 631
Happy的楠姐
Happy的楠姐 2020-12-06 03:37

In the code below, I\'d like the while loop to exit as soon as a + b + c = 1000. However, testing with

相关标签:
6条回答
  • 2020-12-06 03:40

    The while loop will match the condition only when the control returns back to it, i.e when the for loops are executed completely. So, that's why your program doesn't exits immediately even though the condition was met.

    But, in case the condition was not met for any values of a,b,c then your code will end up in an infinite loop.

    You should use a function here as the return statement will do what you're asking for.

    def func(a,b,c):
        for a in range(3,500):
            for b in range(a+1,500):
                c = (a**2 + b**2)**0.5
                if a + b + c == 1000:
                    print a, b, c
                    print a*b*c
                    return # causes your function to exit, and return a value to caller
    
    func(3,4,5)
    

    Apart from @Sukrit Kalra's answer, where he used exit flags you can also use sys.exit() if your program doesn't have any code after that code block.

    import sys
    a = 3
    b = 4
    c = 5
    for a in range(3,500):
        for b in range(a+1,500):
            c = (a**2 + b**2)**0.5
            if a + b + c == 1000:
                print a, b, c
                print a*b*c
                sys.exit()     #stops the script
    

    help on sys.exit:

    >>> print sys.exit.__doc__
    exit([status])
    
    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is numeric, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).
    
    0 讨论(0)
  • 2020-12-06 03:46

    You can wrap with try/excep and raise when the condition is met.

    class FinitoException(Exception):
        pass
    
    a = 3
    b = 4
    c = 5
    x = 0
    try:
      for a in range(3,500):
          for b in range(a+1,500):
              c = (a**2 + b**2)**0.5
              if a + b + c == 1000:
                  print a, b, c
                  print a*b*c
                  raise FinitoException()
    except FinitoException:
        return # or whatever
    
    0 讨论(0)
  • 2020-12-06 03:46

    You could use a break statement:

    a = 3
    b = 4
    c = 5
    x = 0
    while x != 1:
        for a in range(3,500):
            for b in range(a+1,500):
                c = (a**2 + b**2)**0.5
                if a + b + c == 1000:
                    print a, b, c
                    print a*b*c
                    break
    
    0 讨论(0)
  • 2020-12-06 03:55

    You can refactor the inner code into a function and use return to exit:

    def inner():
        for a in range(3,500):
            for b in range(a+1,500):
                c = (a**2 + b**2)**0.5
                if a + b + c == 1000:
                    print a, b, c
                    print a*b*c
                    return False
        return True
    
    while inner():
        pass
    

    Have a look at this question.

    0 讨论(0)
  • 2020-12-06 04:02

    The problem is, even though you set x=1 when a+b+c==1000, you do not break out of the two for loops when that condition is met, and so the while loop doesn't know that x==1 until both for loops finish. To avoid this problem, you can add explicit break statements to the for loops (and as Sukrit Kalra points out, the while loop becomes unnecessary).

    a = 3
    b = 4
    c = 5
    x = 0
    for a in range(3,500):
      for b in range(a+1,500):
         c = (a**2 + b**2)**0.5
         if a + b + c == 1000:
            print a, b, c
            print a*b*c
            x = 1
            break
      if x==1:
         break
    
    0 讨论(0)
  • 2020-12-06 04:04

    If you don't want to make a function ( which you should and refer to Ashwini's answer in that case), here is an alternate implementation.

    >>> x = True
    >>> for a in range(3,500):
            for b in range(a+1, 500):
                c = (a**2 + b**2)**0.5
                if a + b + c == 1000:
                     print a, b, c
                     print a*b*c
                     x = False
                     break
             if x == False:
                break
    200 375 425.0
    31875000.0
    
    0 讨论(0)
提交回复
热议问题