Python For Loops
Welcome to our tutorial on For Loops in Python!
For loops are one of the most important constructs in Python for iterating over sequences of data, such as lists, tuples, and strings. In this tutorial, we’ll cover the basics of for loops and show you how to use them in your own programs.
What is a For Loop?
A for loop is a way to iterate over a sequence of values in Python. It consists of a loop variable, which takes on each value in the sequence in turn, and a block of code that is executed once for each value of the loop variable.
Here’s the basic syntax for a for loop in Python:
for <variable> in <sequence>:
<code block>
The loop variable takes on each value in the sequence one at a time, and the code block is executed once for each value.
Iterating over Lists
One of the most common uses of for loops in Python is to iterate over the elements in a list. Here’s an example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
This will output:
apple
banana
cherry
The loop variable fruit
takes on each value in the fruits
list in turn, and the print
statement is executed once for each value.
Range Function
The range()
function is often used with for loops to generate a sequence of numbers. Here’s an example:
for i in range(5):
print(i)
This will output:
0
1
2
3
4
The loop variable i
takes on each value in the sequence generated by range(5)
, which is [0, 1, 2, 3, 4]
.
Nested Loops
For loops can also be nested inside one another to iterate over multiple sequences at the same time. Here’s an example:
for i in range(3):
for j in range(2):
print(i, j)
This will output:
0 0
0 1
1 0
1 1
2 0
2 1
The outer loop iterates over the sequence [0, 1, 2]
, and the inner loop iterates over the sequence [0, 1]
. The print
statement is executed once for each combination of values.
Conclusion
For loops are a powerful tool in Python for iterating over sequences of data. This lesson in our python tutorial should teach you mostly everything needed to start. By understanding the basics of for loops, you can write more efficient and effective code in your own programs. Continue following our tutorial documentation here at Whitewood Media & Web Development. Practice writing for loops on your own, and you’ll be well on your way to mastering this important concept in Python programming.