Loop Statements
What Are Loop Statements?
- Loop statements help us execute a block of code multiple times. They repeat until a specific condition is met or for each item in a collection.
Types of Loop Statements:
- For Loop:
- Used to run a block of code for each element in a collection.
Example:
pythonlist_1 = ['apple', 'banana', 'cherry'] for item in list_1: print(item)Output:
apple banana cherry
- While Loop:
- Used to run a block of code as long as a condition is true.
Example:
pythonlist_1 = ['apple', 'banana', 'cherry'] index = 0 while index < len(list_1): print(list_1[index]) index += 1Output:
apple banana cherry
Using for i in range():
Execute a block of code for each number in a given range.
pythonfor i in range(5): print(i)Output:
0 1 2 3 4
Loop Controls:
- Break:
- Continue:
Summary:
- Loop statements are vital for repeating actions in your code. Using for and while loops, along with break and continue, allows you to control how and when blocks of code are executed multiple times. Practice these concepts with the exercises to become proficient in using loops in Python!