For loops are an essential tool in programming that allows you to iterate over a sequence (such as a list, tuple, or string) or other iterable objects (such as a dictionary) and execute a block of code for each item in the sequence. In this article, we will cover the basic syntax for for loops, provide examples of how to use them to iterate over different types of sequences, and show you how to use the break and continue statements to exit a loop early or skip iterations. By the end of this article, you should have a good understanding of how to use for loops in Python and be able to apply them in your own code.
A for loop in Python allows you to iterate over a sequence (such as a list, tuple, or string) or other iterable objects (such as a dictionary) and execute a block of code for each item in the sequence.
Here is the basic syntax for a for loop in Python:
for item in sequence: # code to be executed
Python for Loop on List
Here is an example of a for loop that iterates over a list of numbers and prints each one:
numbers = [1, 2, 3, 4, 5] for number in numbers: print(number)
This will output the following:
1 2 3 4 5
Python for Loop on range()
You can also use the range() function to specify the number of times the loop should iterate. For example:
for i in range(5): print(i)
This will output the following:
0 1 2 3 4
Python for Loop on enumerate()
You can also use the enumerate() function to iterate over a list and access both the index and value of each item in the list. For example:
fruits = ['apple', 'banana', 'mango'] for i, fruit in enumerate(fruits): print(i, fruit)
This will output the following:
0 apple 1 banana 2 mango
Python for Loop on dictionary
You can also use a for loop to iterate over a dictionary, accessing the keys and values of each item. For example:
prices = {'apple': 0.5, 'banana': 0.25, 'mango': 0.75} for fruit, price in prices.items(): print(fruit, price)
This will output the following:
apple 0.5 banana 0.25 mango 0.75
Python for Loop : break statement and continue statement
You can use the break statement to exit a for loop early, and the continue statement to skip the rest of the current iteration and move on to the next one. For example:
for i in range(10): if i == 5: break print(i)
This will output the following:
0 1 2 3 4
for i in range(10): if i % 2 == 0: continue print(i)
This will output the following:
1 3 5 7 9
We hope these examples help to demonstrate how to use for loops in Python. Let me know if you have any questions or need further clarification.