Learn Python
Lesson 1 - Introduction To Python
Lesson 2 - Basic Python Syntax
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 6 - Exception Handling
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
Loops in Python allow you to execute a block of code repeatedly, making it efficient for tasks that require repetitive operations.
for
Loop:The for
loop is used to iterate over a sequence such as a list, tuple, or string. Here’s how you create a for
loop:
fruits = ["orange", "banana", "apple"] for fruit in fruits: print(fruit)
In this example, the for
loop iterates through each item in the fruits
list and prints it.
while
Loop:The while
loop executes a block of code as long as a specified condition is True
. For example:
count = 0 while count < 5: print(count) count += 1
This while
loop runs until the count
variable is less than 5. The count += 1
statement increments count
by one with each iteration.
break
Statement:The break
keyword interrupts the loop execution immediately when a certain condition is met. For instance:
count = 0 while count < 5: if count == 3: break print(count) count += 1
In this example, the loop stops as soon as count
equals 3, due to the break
statement.
continue
Statement:The continue
keyword skips the current iteration of the loop when a specified condition is True
. For example:
count = 0 while count < 5: if count == 3: count += 1 continue print(count) count += 1
Here, the loop skips printing when count
equals 3, but continues with the next iteration.
These control flow statements (break
and continue
) are powerful tools for managing loop execution based on specific conditions in Python.