In Python, loops are used to repeatedly execute a block of code. There are two main types of loops: for loops and while loops. Let’s discuss them in detail.
for loops:
Basic Syntax: In python we use.
for variable in iterable:
# code to be executed in each iteration
iterable: An object capable of returning its elements one at a time (e.g., lists, tuples, strings, etc.).
variable: A variable that takes the value of the next element in the iterable in each iteration.
Example:
fruits = [‘apple’, ‘banana’, ‘cherry’]
for fruit in fruits:
print(fruit)
Range-based for loop:
Basic Syntax: In python we use
for i in range(start, stop, step):
# code to be executed in each iteration
start: Starting value (default is 0).
stop: Ending value (not inclusive).
step: Step size (default is 1).
Example:
for i in range(1, 6):
print(i)
while loops:
Basic Syntax: In python we use
while condition:
# code to be executed as long as the condition is True
Example:
count = 0
while count < 5:
print(count)
count += 1
Loop Control Statements:
break:
– Terminates the loop prematurely.
Example:
for char in “python”:
if char == ‘h’:
break
print(char)
continue:
– Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
Example:
for char in “python”:
if char == ‘h’:
continue
print(char)
else clause:
– Executed when the loop condition becomes False.
Example:
for i in range(5):
print(i)
else:
print(“Loop finished”)
Nested Loops:
You can have loops inside other loops.
Example:
for i in range(3):
for j in range(2):
print(i, j)
This will produce a Cartesian product of the two ranges.
These are the fundamentals of loops in Python. They are powerful constructs for iterating over data and performing repetitive tasks.
share with your coding friends.
comment for more.
Comments are closed.