Python loops
Loops are a fundamental concept in programming that allow you to repeat a block of code multiple times. Python supports two main types of loops: "for" loops and "while" loops. These loops are used to automate repetitive tasks and iterate through collections of data. Here's an introduction to both types of loops:
- For Loops:
A "for" loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence.
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
In this example, the "for" loop iterates over each item in the "fruits" list and prints each fruit name.
You can also use the range() function to generate a sequence of numbers to iterate over:
for num in range(1, 6):
print(num)
This loop will print the numbers 1 to 5.
A "while" loop repeatedly executes a block of code as long as a specified condition is true.
count = 0
while count < 5:
print(count)
count += 1
In this example, the "while" loop will keep printing the value of "count" as long as it's less than 5. The loop will terminate when the condition becomes false.
Both "for" and "while" loops can be controlled using certain statements:
- break: Terminates the loop prematurely.
- continue: Skips the rest of the current iteration and moves to the next iteration.
- else (for "for" loops): Executes a block of code when the loop completes normally (i.e., not interrupted by a "break").
Be careful with loops to avoid creating infinite loops—loops that never stop. Make sure that your loop's condition can eventually become false, or use techniques like incrementing a counter or breaking the loop explicitly.
- Use a "for" loop when you know the number of iterations beforehand (e.g., iterating through a list).
- Use a "while" loop when you're unsure about the number of iterations or need to repeatedly execute code until a certain condition is met.
Loops are vital tools for automating repetitive tasks, iterating through data, and controlling the flow of your program based on conditions.