Can you show another nested loop example?

QuestionsQuestions4 SkillsProPython Control StructuresOct, 01 2025
0174

Certainly! Here's another example of nested loops in Python, this time to create a multiplication table:

Example: Multiplication Table

# Define the size of the multiplication table
size = 5

# Outer loop for the rows
for i in range(1, size + 1):
    # Inner loop for the columns
    for j in range(1, size + 1):
        # Print the product
        print(f"{i * j:4}", end=' ')  # Format for better alignment
    print()  # New line after each row

Output

This will produce a 5x5 multiplication table:

   1   2   3   4   5 
   2   4   6   8  10 
   3   6   9  12  15 
   4   8  12  16  20 
   5  10  15  20  25 

Explanation

  • The outer loop (for i in range(1, size + 1)) iterates through the numbers 1 to 5, representing the rows.
  • The inner loop (for j in range(1, size + 1)) also iterates through the numbers 1 to 5, representing the columns.
  • Inside the inner loop, the product of i and j is calculated and printed, formatted for alignment.
  • After the inner loop completes, print() is called to move to the next line for the next row of the table.

This example demonstrates how nested loops can be used to generate structured output. If you have any other questions or need further examples, let me know!

0 Comments

no data
Be the first to share your comment!