Loops in Python allow you to repeatedly execute a block of code as long as a certain condition is met. There are two main types of loops in Python: for
loops and while
loops. Let's go through each of them with examples:
for
LoopA for
loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each element in the sequence.
for
Loop ExampleOutput:
for
Loop with range()
The range()
function generates a sequence of numbers, which can be useful for iterating a specific number of times.
Output:
while
LoopA while
loop repeatedly executes a block of code as long as the specified condition is True
.
while
Loop ExampleOutput:
The break
statement is used to exit the loop prematurely when a certain condition is met.
Output:
The continue
statement skips the current iteration and moves to the next iteration of the loop.
Output:
You can use loops inside other loops (nested loops) to perform more complex iterations.
for
Loop ExampleOutput:
Here's a practical example that combines loops and conditions:
Output:
Loops are a fundamental part of Python that allow you to automate repetitive tasks and handle sequences of data efficiently. If you have any specific questions or need further examples, feel free to ask! ??