Python Loops
In Python, you can use loops to
repeatedly execute a block of code. There are two main types of loops: for
loops and while
loops.
for
loop:
The for
loop is used to iterate over a sequence (such as a list, tuple,
string, or range).
Example:
# Iterating over a list
fruits = [
"apple",
"banana",
"cherry"]
for fruit
in fruits:
print(fruit)
#
Iterating over a range
For i
in
range(
5):
print(i)
while
loop:
The while
loop is used to repeatedly execute a block of code as long as a
given condition is true.
Example:
#
Using a while loop to print numbers from 0 to 4
count =
0
while count <
5:
print(count) count +=
1
# Increment the counter
Loop Control
Statements:
Python
also provides loop control statements to modify the execution of loops:
break
: Terminates the loop and transfers control to the statement
immediately after the loop.
continue
: Skips the rest of the code inside the loop for the current
iteration and moves to the next iteration.
Example:
#
Using break to exit a loop prematurely
for i
in
range(
10):
if i ==
5:
break
print(i)
# Using continue to skip an
iteration
for i
in
range(
5):
if i ==
2:
continue
print(i)
These examples provide a basic overview of looping in Python. Depending on
the specific task, you might choose between for
and while
loops, and use loop control statements when needed
Comments
Post a Comment