About Lesson
๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Understand and use the
break
andcontinue
statements -
Control the flow of loops dynamically
-
Avoid infinite loops by using
break
-
Skip iterations using
continue
๐ Lesson Content
๐น What is break
in Python?
break
is used to exit a loop prematurely โ as soon as the break
line is reached, the loop stops.
โ Example:
Output:
๐ง The loop stops when
i == 5
.
๐น What is continue
in Python?
continue
is used to skip the current iteration of a loop and jump to the next one.
โ Example:
Output:
๐ง The number
3
is skipped, not printed.
๐ Comparison Table
Statement | Function |
---|---|
break |
Exits the loop entirely |
continue |
Skips current iteration, continues loop |
ย
๐ธ Using with while
Loop
โ ๏ธ Common Pitfalls
Mistake | Why itโs a problem |
---|---|
Forgetting i += 1 |
Can cause infinite loop |
Using continue without care |
Can skip essential logic |
break outside loop |
Causes a SyntaxError |
ย
๐ง Mini Exercise
-
Write a loop from 1 to 10
-
Use
continue
to skip number 6 -
Use
break
to stop the loop after 8
๐ Assignment
Create a program that:
-
Asks the user for numbers repeatedly
-
If the number is negative,
continue
(skip it) -
If the number is
0
,break
the loop -
Otherwise, print the square of the number