Learn all about loops in Python
In Python, loops are control structures that allow you to repeatedly execute a block of code. They help you automate repetitive tasks and make your code more efficient. Python supports two main types of loops: for and while.
1. For Loop:
The for loop is used for iterating over a sequence (that is either a list, tuple, dictionary, string, or other iterable objects). The basic syntax of a for loop is:for variable in sequence: # code to be executed
Here, variable takes the value of each item in the sequence one by one, and the indented code block under the loop is executed for each iteration.
Example:
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
Output:apple banana cherry
2. While Loop:
The while loop repeats a block of code as long as a specified condition is true. The syntax is:while condition: # code to be executed
The loop continues until the condition becomes false.
Example:
count = 0 while count < 5: print(count) count += 1
Output:0 1 2 3 4
Loop Control Statements:
a. break Statement:
The break statement is used to exit the loop prematurely. When encountered, the loop immediately terminates.for i in range(5): if i == 3: break print(i)
Output:0 1 2
b. continue Statement:
The continue statement is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.for i in range(5): if i == 2: continue print(i)
Output:0 1 3 4
Loop with else:
Both for and while loops can have an optional else block which is executed when the loop condition becomes false.for i in range(5): print(i) else: print("Loop finished")
Output:0 1 2 3 4 Loop finished
These are the basic concepts of loops in Python. Understanding how to use loops is fundamental for writing efficient and concise code.
Watch Now:- https://www.youtube.com/watch?v=PzXlHzmm-V4













