How To Use Loops in Python

Loops are a key programming construct in Python that allow you to execute a block of code repeatedly. The two most common types of loops are for loops and while loops. For loops are used to iterate over a sequence of values, such as a list, and execute a block of code for each value.

While loops are used to execute a block of code repeatedly while a certain condition is true. Nested loops, where a loop is contained within another loop, are also common. Looping is a powerful way to automate repetitive tasks in programming and is an essential concept to master in Python.

Here are examples of Python scripts that use different types of loops:

  1. For Loop
    1. # Example of a for loop that prints the numbers 1 to 5
    2. for i in range(1, 6):
    3.     print(i)
    4.    
    5. # Output:
    6. # 1
    7. # 2
    8. # 3
    9. # 4
    10. # 5
  2. Nested For Loop
    1. # Example of a nested for loop that prints a multiplication table
    2. for i in range(1, 11):
    3.     for j in range(1, 11):
    4.         print(i * j, end='\t')
    5.     print()
    6.  
    7. # Output:
    8. # 1     2       3       4       5       6       7       8       9       10     
    9. # 2     4       6       8       10      12      14      16      18      20     
    10. # 3     6       9       12      15      18      21      24      27      30     
    11. # 4     8       12      16      20      24      28      32      36      40     
    12. # 5     10      15      20      25      30      35      40      45      50     
    13. # 6     12      18      24      30      36      42      48      54      60     
    14. # 7     14      21      28      35      42      49      56      63      70     
    15. # 8     16      24      32      40      48      56      64      72      80     
    16. # 9     18      27      36      45      54      63      72      81      90     
    17. # 10    20      30      40      50      60      70      80      90      100    
  3. While Loop
    1. # Example of a while loop that prints the first 5 even numbers
    2. count = 1
    3. num = 0
    4. while count <= 5:
    5.     if num % 2 == 0:
    6.         print(num)
    7.         count += 1
    8.     num += 1
    9.  
    10. # Output:
    11. # 0
    12. # 2
    13. # 4
    14. # 6
    15. # 8

In these examples, the for loop is used to iterate over a sequence of values, the nested for loop is used to create a multiplication table, and the while loop is used to print the first 5 even numbers. Understanding how to use different types of loops is an important part of learning to program in Python.

Add new comment