Learn Python
- Python basic
- Introduction to File Handling
- Basics of List Comprehension
- Introduction to Matplotlib
- Classes and Objects
- Introduction to Functions
- Python Numbers
- Creating Basic Plots
- Opening and closing files
- Function parameters and arguments
- Advanced Techniques
- Attributes and Methods
- Python Strings
- Scope and lifetime of variables
- Advanced Plotting
- Reading from files
- Performance and Limitations
- Encapsulation
- Python List
- Specialized Plots
- Writing to files
- Return statement and output
- Inheritance
- Python Tuple
- Advanced Customization
- Working with different file formats
- Lambda Functions
- Polymorphism
- Python Sets
- File management operations
Flow control
Break and continue
In a while loop (or any loop like for), break and continue are control flow statements that affect how the loop operates, but they work in different ways:
1. break:
It immediately terminates the loop. When break is encountered, the program exits the loop entirely and continues executing the code that follows the loop.
Example:
1. break:
It immediately terminates the loop. When break is encountered, the program exits the loop entirely and continues executing the code that follows the loop.
Example:
i = 1 while i <= 5: if i == 3: break # Loop will exit when i is 3 print(i) i += 1
Output:
1 2
Here, when i becomes 3, the break statement is executed, causing the loop to end.
2. continue:
It skips the current iteration of the loop and moves on to the next iteration.
When continue is encountered, the rest of the code inside the loop for the current iteration is skipped, but the loop continues from the next iteration.
Example:
i = 1 while i <= 5: i += 1 if i == 3: continue # Loop will skip printing when i is 3 print(i)
Output:
2 4 5 6
Here, when i is 3, the continue statement is executed, so the print(i) statement is skipped for that iteration, but the loop continues for the next iterations.
It's time to take a quiz!
Test your knowledge and see what you've just learned.
What does the break statement do in a loop?
DIt causes an error
AIt skips the current iteration of the loop
BIt immediately terminates the loop
CIt restarts the loop from the beginning
Check Answer
What does the continue statement do in a loop?
AIt skips the current iteration and moves to the next one
BIt exits the loop completely
CIt restarts the loop from the beginning
DIt causes an error
Check Answer
What will be the output of the following code? i = 1 while i <= 5: i += 1 if i == 3: continue print(i)
D2
3
4
5
A1
2
3
4
5
B1
2
4
5
C2
4
5
Check Answer