Week 5: Automating Repetitive Tasks with Loops
Learn how to use `for` and `while` loops in Python to execute code repeatedly.
Explore Chapter 5`break` and `continue` Statements: Controlling Loop Execution.
The `break` and `continue` statements provide ways to alter the normal flow of `for` and `while` loops.
`break` Statement
The `break` statement immediately terminates the loop it is inside of. The program control then flows to the statement immediately following the loop.
numbers = [1, 2, 3, 4, 5, -1, 6, 7]
for num in numbers:
if num < 0:
print("Negative number found! Exiting loop.")
break
print("Number is:", num)
Output:
Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
Negative number found! Exiting loop.
`continue` Statement
The `continue` statement skips the rest of the code inside the current iteration of the loop and proceeds to the next iteration.
numbers = [1, 2, -3, 4, -5, 6]
for num in numbers:
if num < 0:
print("Negative number encountered. Skipping.")
continue
print("Positive number is:", num)
Output:
Positive number is: 1
Positive number is: 2
Negative number encountered. Skipping.
Positive number is: 4
Negative number encountered. Skipping.
Positive number is: 6