How To Exit For Loop In Python?

exit for loop in python

By default, the loop in Python will iterate from the beginning to the end of the loop. That does not optimize the execution speed of our application. So today, we will show you how to exit for loop in Python to optimize your project.

Four simple ways to exit for loop in Python

Here are 4 ways we want to recommend to you. Read on and find out the best way for you.

Using break keyword

The break keyword in Python is used to break out of a loop in Python. Python will force loops to stop when the break statement is executed. We usually use it in the switch case statements, but we can also use it for the for loop. Like this:

my_str = "learnshareit.com"

# Print from the beginning to the dot
for c in my_str:
    # Exit if char in the current loop = '.'
    if c == '.':
        break # Exit the for loop
    
    print(c, end = "") # Print on the same line

Output:

learnshareit

Using quit() function

The quit() function is a built-in function of Python. We can use the quit() statement anywhere in the program where we want it to stop. Like the below:

my_str = "learnshareit.com"

# Print 'learn'
for c in my_str:
    # Exit if char in the current loop = 's'
    if c == 's':
        quit()  # Quit the for loop
    
    print(c, end = "") # Print on the same line

Output:

learn

Using exit() function

The exit() function is also a built-in function of Python. In essence, exit() is the alias of quit(). In function, they are identical and differ only in spelling. So we can use exit() instead of quit().

my_str = "learnshareit.com"

# Print 'learn'
for c in my_str:
    # Exit if char in the current loop = 's'
    if c == 's':
        exit()  # Exit the for loop
    
    print(c, end = "") # Print on the same line

Output:

learn

Using sys.exit() function

Syntax:

sys.exit(msg)

Parameter:

  • msg (optional): an error message you can set.

Unlike exit(), sys.exit() stops the program and returns a message set by you. In practice, we should use sys.exit() instead of exit() or quit().

See the example below for how to use sys.exit():

# Import sys module
import sys

my_str = "learnshareit.com"

for c in my_str:
    # Exit if char in the current loop = 's'
    if c == 's':
      # Exit the for loop with the message
      sys.exit("Message: Unable to continue printing")
      
    print(c)

Output:

l
e
a
r
n
Message: Unable to continue printing

Summary

To sum up, we’ve learned 4 ways to exit for loop in Python. We recommend using the break keyword to make your code more concise and readable.

Happy coding!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *