The for
loop in Python is used to iterate over a sequence of items, executing a block of code for each item in the sequence. It is a versatile and powerful tool for performing repetitive tasks efficiently.
Syntax:
for item in sequence:
# Code block to execute for each item
statement1
statement2
...
Explanation:
- The
for
keyword initiates the loop. item
is a variable that represents each item in the sequence during each iteration of the loop.sequence
is any iterable object that contains the items to iterate over, such as a string, range, or other iterable.- The code block indented under the
for
statement is executed for each item in the sequence.
Using the in
Operator:
- The
in
operator is used to check for the presence of an item in a sequence. - It returns
True
if the item is found in the sequence, andFalse
otherwise.
Using the range()
Method:
- The
range()
method is used to generate a sequence of numbers within a specified range. - It takes up to three arguments:
start
,stop
, andstep
. start
(optional): The starting value of the range (default is 0).stop
: The end value of the range (exclusive).step
(optional): The increment between each number in the range (default is 1).
Example: Printing Numbers from 1 to 5
for num in range(1, 6): # Range from 1 to 5 (inclusive start, exclusive end)
print(num)
Explanation:
- In this example, the
range(1, 6)
method generates a sequence of numbers from 1 to 5. - The
for
loop iterates over each number in the sequence, assigning it to the variablenum
during each iteration. - The
print(num)
statement prints each number in the sequence.
Example: Summing Numbers from 1 to 10
total = 0
for num in range(1, 11): # Range from 1 to 10 (inclusive start, exclusive end)
total += num
print("Sum of numbers from 1 to 10:", total)
Explanation:
- In this example, the
total
variable is initialized to 0. - The
for
loop iterates over each number in the sequence generated byrange(1, 11)
. - During each iteration, the current number is added to the
total
variable. - After the loop completes, the total sum of numbers from 1 to 10 is printed.
Using input()
and Type Casting:
n = int(input("Enter the number of iterations: "))
for i in range(n):
print("Iteration", i+1)
Explanation:
- In this example, the user inputs the number of iterations (
n
) for the loop using theinput()
method. - The input string is converted to an integer using the
int()
function to determine the range for the loop. - The loop iterates
n
times, withi
ranging from 0 ton-1
. - Each iteration number is printed, starting from 1.
Key Points:
- The
for
loop is used to iterate over a sequence of items. - The
in
operator checks for the presence of an item in a sequence. - The
range()
method generates a sequence of numbers within a specified range. - Proper indentation is crucial for defining the code block inside the loop.
input()
and type casting can be used to make the loop more interactive, allowing user input to control the loop's behavior.
Nested loops in Python refer to the situation where you have one loop (inner loop) inside another loop (outer loop). This structure allows you to iterate over elements in a more complex manner, often useful for iterating through multidimensional data structures like matrices or nested lists.
Syntax:
for outer_item in outer_sequence:
for inner_item in inner_sequence:
# Code block to execute for each inner item
statement1
statement2
...
# Code block to execute after inner loop completes (optional)
statement3
statement4
...
# Code block to execute after outer loop completes (optional)
statement5
statement6
...
Explanation:
- The outer loop iterates over each item in the outer sequence.
- For each iteration of the outer loop, the inner loop iterates over each item in the inner sequence.
- The code block inside the inner loop is executed for each combination of outer and inner items.
- After completing the inner loop for each outer item, the code block after the inner loop (if present) is executed.
- Finally, after completing all iterations of the outer loop, the code block after the outer loop (if present) is executed.
Example: Multiplication Table
Let's use nested loops to generate a multiplication table:
for i in range(1, 11):
for j in range(1, 11):
print(i, "x", j, "=", i * j)
print() # Print a blank line after each row
Explanation:
- The outer loop (
for i in range(1, 11)
) iterates over the multiplicand (numbers from 1 to 10). - For each value of
i
, the inner loop (for j in range(1, 11)
) iterates over the multiplier (also numbers from 1 to 10). - Inside the inner loop, the product of
i
andj
is calculated and printed as a part of the multiplication table. - After each row (i.e., after completing the inner loop for a specific
i
), a blank line is printed to separate the rows visually.
Example: Pattern Printing
Nested loops can also be used to print patterns, such as a triangle:
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print("*", end=" ")
print() # Move to the next line after each row
Explanation:
- The outer loop controls the number of rows to be printed.
- The inner loop controls the number of stars (
*
) to be printed in each row. - The number of stars in each row is equal to the row number (
i
) in the outer loop. - After printing the stars for each row, the inner loop moves to the next line (
print()
statement) to start a new row.
Key Points:
- Nested loops are useful for iterating over multidimensional data structures or for performing repetitive tasks that require multiple levels of iteration.
- Pay attention to proper indentation to maintain the hierarchy of the loops and the associated code blocks.
- Nested loops can have any number of levels, but excessive nesting should be avoided for the sake of code readability and maintainability.