1

I want to end a for loop if there is an exception error. And when i use break statement it doesn't end the loop but when i used sys.exit() it ends the loop just ok.

The code i wrote is for calculating ip addresses, but this function below checks if a given ip address have 4 octets and also checks if an octet is an integer value.

This works ok but i don't know if it's efficient to do that. I'm beginner in Python and i wanted to understand the difference between the two.

    def check_octet_range(self):
        if len(self.ip_address_list) == 4:
            for ip_index, address in enumerate(self.ip_address_list, start=1):
                try:
                    address = int(address)
                except ValueError:
                    print(f"Please enter an integer number at octet {ip_index}")
                    sys.exit()
                if address not in self.octet_range:
                    return ip_index

            return self.ip_address_list
        else:
            print("The IP address range is more or less than 4 octet")
            sys.exit()
Kwame Benqazy
  • 45
  • 1
  • 6
  • Try doing something _else_ after `break` or `sys.exit()`. E.g., just `print("at end")` fully outdented, after you call `check_octet_range()`. – ChrisGPT was on strike Jun 22 '20 at 01:31
  • 2
    After reading the relevant documentation, what are some hypothesis on how they may differ? - See [sys.exit](https://docs.python.org/3/library/sys.html#sys.exit) and ["break and continue Statements.."](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) – user2864740 Jun 22 '20 at 01:33
  • 1
    p.s. _both_ forms will "end the loop" _shown_ in the code. Perhaps the code should use a `return` (to return from the function) instead of a `break` (to exit the loop)? – user2864740 Jun 22 '20 at 01:40
  • 1
    [`break`](https://docs.python.org/3/reference/simple_stmts.html#break) breaks out of loops, while [`sys.exit()`](https://docs.python.org/3/library/sys.html#sys.exit) triggers the interpreter to exit through the documented method. Please consult the documentation and search elsewhere online as fundamental questions like these are often discussed [previously elsewhere](https://python-forum.io/Thread-whats-the-difference-between-sys-exit-and-break). If you want to "exit" from an `if` clause [this question](https://stackoverflow.com/questions/2069662/how-to-exit-an-if-clause) is titled that. – metatoaster Jun 22 '20 at 01:41
  • What is the *similarity*? – Karl Knechtel Jun 22 '20 at 02:11

2 Answers2

4
  • break is used to exit a loop

  • sys.exit() is used to terminate the running program.

bhristov
  • 3,137
  • 2
  • 10
  • 26
2

A "break" is only allowed in a loop (while or for), and it causes the loop to end but the rest of the program continues.

On the other hand "sys.exit()" aborts the execution of the current program and passes control to the environment.