Loops in Python
Introduction to Loops:
Loops in programming are used to execute a block of code repeatedly until a certain condition is met. In Python, there are two main types of loops: for
loops and while
loops.
1. for
Loops:
A for
loop is used to iterate over a sequence (such as a list, tuple, dictionary, or string) and execute a block of code for each item in the sequence.
Syntax:
for item in sequence:
# code block to be executed
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. while
Loops:
A while
loop is used to repeatedly execute a block of code as long as a condition is true.
Syntax:
while condition:
# code block to be executed
Example:
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Loop Control Statements:
Python provides loop control statements to alter the flow of loops.
1. break
Statement:
The break
statement is used to exit the loop prematurely, regardless of whether the loop condition has been fulfilled or not.
Example:
for num in range(10):
if num == 5:
break
print(num)
Output:
0
1
2
3
4
2. continue
Statement:
The continue
statement is used to skip the rest of the code inside the loop for the current iteration and proceed to the next iteration.
Example:
for num in range(10):
if num == 5:
continue
print(num)
Output:
0
1
2
3
4
6
7
8
9
3. else
Clause:
Python allows an optional else
block in loops, which is executed if the loop completes normally (i.e., without encountering a break
statement).
Example:
for num in range(5):
print(num)
else:
print("Loop completed normally.")
Output:
0
1
2
3
4
Loop completed normally.
Conclusion:
Loops are powerful constructs in Python that allow you to execute code repeatedly. Whether you need to iterate over a sequence or perform an action until a certain condition is met, loops are essential tools in your programming arsenal. Practice using loops in your code to become proficient in their usage!
Watch Now:- https://www.youtube.com/watch?v=as8vd_610HA