Python Indentation

Top 10 python examples using break and continue statements

The break and continue statements are essential tools in programming that allow you to control the flow of your code within loops. They are commonly used in various programming languages, such as Python, Java, C++, and more.This section provides code examples to demonstrate usage of break and continue statements.

Python One Liners

1. Skipping Odd Numbers:

for i in range(1, 11):
    if i % 2 == 1:
        continue
    print(i)

In this example, the “continue” statement skips odd numbers and continues with the next iteration of the loop.

2. Finding Prime Numbers:

for num in range(2, 20):
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            break
    else:
        print(num, "is prime")

Here, the “break” statement is used to exit the inner loop early when a factor of the number is found.

3. Terminating a Loop:

int[] numbers = { 1, 2, 3, 4, 5 };
for (int num : numbers) {
    if (num == 3) {
        break;
    }
    System.out.println(num);
}

This Java code snippet demonstrates the “break” statement’s ability to terminate a loop prematurely.

4. Searching in a List:

numbers = [10, 20, 30, 40, 50]
search_value = 30
for num in numbers:
    if num == search_value:
        print("Found:", num)
        break
else:
    print("Not found")

The “else” block here is executed when the loop completes normally without encountering a “break” statement.

5. Password Verification:

password = "secret"
attempts = 3
while attempts > 0:
    input_password = input("Enter password: ")
    if input_password == password:
        print("Access granted")
        break
    else:
        print("Incorrect password")
        attempts -= 1

In this example, the loop breaks when the correct password is entered or when the maximum number of attempts is reached.

6. Exiting Nested Loops:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i + j > 4) {
            break;
        }
        System.out.println(i + " " + j);
    }
}

The “break” statement can also be used to exit multiple levels of nested loops, as demonstrated in this Java code snippet.

7. Skipping Outer Iterations:

for i in range(1, 6):
    for j in range(1, 4):
        if j == 2:
            break  # Skip second iteration of inner loop
        print(i, j)

Here, the “break” statement affects only the inner loop and skips the second iteration for each outer loop iteration.

8. Simulating a Menu:

while True:
    choice = input("Select an option (1-3): ")
    if choice == "1":
        print("Option 1 selected")
    elif choice == "2":
        print("Option 2 selected")
    elif choice == "3":
        print("Exiting...")
        break
    else:
        print("Invalid choice")

This example uses a loop to simulate a menu, and the “break” statement is used to exit the loop when the user chooses to exit.

9. Printing Even Numbers:

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 1) {
        continue;
    }
    cout << i << " ";
}

In C++, the “continue” statement can be used to skip iterations and focus on even numbers in this case.

10. Password Retry with Warning:

password = "secure"
attempts = 3
while attempts > 0:
    input_password = input("Enter password: ")
    if input_password == password:
        print("Access granted")
        break
    else:
        print("Incorrect password")
        attempts -= 1
        if attempts == 0:
            print("Out of attempts. Please contact support.")
            break
        print("You have", attempts, "attempts remaining.")

This Python example combines the use of “break” and contextual information to handle password retries.

These examples highlight the utility of the “break” and “continue” statements in various scenarios. By incorporating them into your coding toolkit, you can write more efficient and dynamic code that responds to specific conditions and requirements. Remember to adapt these examples to the programming language you’re using and explore further applications in your projects!

FAQs for break and continue statements

Q1: What is the break statement in Python?

Answer: The break statement is used to exit the closest enclosing loop (for or while) immediately, regardless of the loop condition.

Q2: What is the continue statement in Python?

Answer: The continue statement skips the remaining code inside the current iteration of the loop and moves to the next iteration.

Q3: Where can I use break and continue statements?

Answer: Both break and continue can be used in for and while loops.

Q4: Can I use break and continue outside a loop?

Answer: No, using break and continue outside a loop will result in a syntax error.

Q5: What happens if I use break inside nested loops?

Answer: A break statement will only exit the loop in which it is directly placed. Outer loops will not be affected unless they also have their own break statements.

Q6: Can continue be used in a for-else or while-else construct?

Answer: Yes, the continue statement will work as expected within the loop. However, the else block will still execute after the loop finishes its iterations.

Q7: How does break affect a for-else or while-else construct?

Answer: If a break statement is executed inside the loop, the else block will be skipped.

Q8: Can I use multiple break or continue statements in a single loop?

Answer: Yes, you can use multiple break or continue statements, but doing so can make the code harder to understand and maintain.

Q9: Can I use break and continue in the same loop?

Answer: Yes, both break and continue can be used in the same loop, each serving its own purpose. However, care should be taken to avoid making the loop logic too complex.

Q10: What is the difference between break and return in a function containing a loop?

Answer: A break will exit the loop and continue with the next statement after the loop. A return will exit the loop and the function, returning a value to the caller if specified.