What is the "for" loop in Python and how to use it?
Table of Contants
Introduction:
A for
loop in Python is a control flow statement that allows you to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in that sequence. Unlike a while
loop, where the number of iterations depends on a condition, the for
loop runs for a fixed number of iterations based on the length of the sequence being looped over.
Basic Syntax of the for
Loop
**item**
: A variable that takes the value of each element in the sequence on each iteration.**sequence**
: The collection (list, tuple, string, etc.) that the loop iterates over.
Example: Basic for
Loop
- The loop iterates over each element in the
fruits
list, printing each fruit: "apple," "banana," and "cherry."
How the for
Loop Works
- The loop picks the first item from the sequence and assigns it to the
item
variable. - It executes the code block for the current
item
. - After the block is executed, the next item in the sequence is assigned to
item
, and the process repeats. - The loop ends when there are no more items in the sequence.
Practical Use Cases for the for
Loop
- Looping Over a List or Tuple:
You can use the for
loop to iterate over the elements of a list, tuple, or any other collection.
Example:
- The loop prints each number in the list.
- Looping Over a String:
The for
loop can be used to iterate over each character in a string.
Example:
- The loop prints each character of the string "Python" on a new line.
- Looping Over a Dictionary:
You can use the for
loop to iterate over the keys and values in a dictionary.
Example:
- The loop prints the names and grades of the students.
The range()
Function with a for
Loop
The range()
function generates a sequence of numbers, making it easy to loop over a specific range of values.
Example:
- The loop prints numbers from 0 to 4. The
range(5)
function generates numbers starting from 0 up to (but not including) 5.
Example: Specifying Start and Step in range()
- This loop prints even numbers between 2 and 10 (not inclusive). The
range(2, 10, 2)
function specifies a start of 2, an end of 10, and a step of 2.
Controlling the for
Loop with break
and continue
1. **break**
Statement:
The break
statement terminates the loop immediately, regardless of whether all items have been iterated over.
Example: Exiting the Loop with break
- The loop prints numbers from 0 to 4 and then stops when
num
equals 5 due to thebreak
statement.
2. **continue**
Statement:
The continue
statement skips the current iteration and moves on to the next one.
Example: Skipping an Iteration with continue
- The loop skips printing the number 3 and continues with the next iteration.
Using the else
Clause with a for
Loop
Python allows an else
clause to be used with a for
loop. The else
block is executed after the loop completes all its iterations unless the loop is terminated with a break
.
Example:
- The
else
block runs after the loop has printed all numbers from 0 to 4, printing "Loop finished."
Practical Examples of Using the for
Loop
1. Summing Numbers in a List:
You can use the for
loop to sum the values in a list.
- The loop adds each number in the list to the
total
, which ends up as 15.
2. Finding Even Numbers:
The for
loop can be used to find and print even numbers in a range.
- This loop checks if each number in the range 1 to 10 is divisible by 2 and prints the even numbers.
3. Nested **for**
Loops:
You can nest for
loops to iterate over multiple dimensions, such as in a matrix or a list of lists.
- The outer loop iterates over rows, and the inner loop iterates over items in each row, printing a 3x3 matrix.
Conclusion:
The for
loop in Python is a versatile control structure that allows you to iterate over sequences like lists, tuples, and strings. It is useful for situations where you need to perform repetitive tasks or process items in a sequence. Combined with features like the range()
function, break
, and continue
statements, the for
loop becomes a powerful tool for efficiently handling iterations in your Python programs.