Understanding Python Loops: Repeating Code with Control Structures
Explore how Python loops enable you to execute a block of code multiple times. Learn about the different types of loops and control structures that help manage repetitive tasks, ensuring efficient and organized code execution. This guide provides a foundational understanding of how loops work in Python.
Python Loops
Python loops let us run a statement or group of statements multiple times.
Usually, statements run one after another, but sometimes you need to repeat a block of code several times. Control structures help manage these repetitive tasks.
Flowchart of a Loop
Here is a diagram illustrating a loop statement:
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
Types of Loops in Python
Python has the following types of loops:
Loop Type | Description |
---|---|
while loop | Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before running the loop body. |
for loop | Runs a sequence of statements multiple times and simplifies managing the loop variable. |
nested loops | You can use one or more loops inside another loop. |
Python Loop Control Statements
Loop control statements change the normal sequence of execution. When leaving a scope, all automatic objects created in that scope are destroyed. Python supports the following control statements:
Control Statement | Description |
---|---|
break statement | Ends the loop and transfers execution to the statement right after the loop. |
continue statement | Skips the rest of the loop body and immediately retests its condition before repeating. |
pass statement | Used when a statement is required syntactically but you do not want any command or code to run. |
Syntax
while condition:
# loop body
Output
Loop executed until condition is false.
Syntax
for item in sequence:
# loop body
Output
Loop executed for each item in sequence.
Syntax
for i in range(5):
for j in range(3):
# nested loop body
Output
Nested loops executed for each combination of i and j.
Syntax
while condition:
if some_condition:
break
Output
Loop terminated with break statement.
Syntax
while condition:
if some_condition:
continue
Output
Loop continued with continue statement.
Syntax
def function():
pass
Output
pass statement used in function.