Loops

Essential for loop example (list)

Python
# list of colors of the rainbow
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

for color in colors:
    print(color) 
# output: print each color in the list colors

range

Python
# for loop with range
for number in range(1, 21):
    print(number) 
# output: print each number from 1 to 20

The range() function in Python is used to generate a sequence of numbers. It is often used in for loops to iterate over a specific range of values. The range(1, 2, 3) Function takes up to three arguments:

  • (1) start: The first number in the field. The default value is 0.
  • (2) stop: The last number in the range. This value is not included in the range.
  • (3) step: The amount by which to increment the sequence. The default value is 1.

Enumerated for loop

Python
# enumerate for loop
fruits = ["apple", "banana", "orange", 'mango'. 'water']
for i, fruit in enumerate(fruits): 
# fruit is the value of the list fruits
# the first variable i is the index and the second variable fruit is the value
    print(f"At position {i}, I found a {fruit}")

The enumerate() function in Python is used to iterate over an iterable object and return an enumerate object. An enumerate object is a tuple (can’t be changed) containing the index and the current item’s value in the iterable object.

The enumerate() function takes two arguments:

  • iterable: The iterable object to iterate over.
  • start: The starting index for the counter. The default value is 0.

The enumerate() function returns an enumerate object, which can be used in a for loop to iterate over the items in the iterable object and get their index and value.

The enumerate() function is useful for iterating over objects, including lists, sets, and tuples.

f in (f"At position {i}, I found a {fruit}") – provide a concise and convenient way to embed Python expressions inside string literals for formatting. (variables)

While Loops

While loops, the condition is a Boolean expression evaluated before executing the loop body. If the condition evaluates to True, the loop body is executed. Once the loop body has been executed, the condition is evaluated again. The loop body is executed again if the condition still evaluates to True. This process continues until the condition evaluates to False, at which point the loop terminates.

Python
    counter = 1 # initialize counter variable
    while counter <= 10: # while loop condition
        print(counter) # print counter variable
        counter += 1 # increment counter variable by 1
    
  1. counter variable is initialized with the value 1.
  2. The while loop is used to repeatedly execute a block of code as long as a given condition is True. In this case, the condition is counter <= 10, meaning the loop will continue if the count is less than or equal to 10.
  3. Inside the loop:
    • The print(counter) statement outputs the current value of the count variable.
    • The count += 1 statement increments the value of counter by 1. This step ensures that the loop will eventually terminate when counter becomes greater than 10.
  4. The loop will continue executing as long as the condition counter <= 10 is satisfied.
  5. The loop will print the numbers 1 to 10 in consecutive order since the print statement is inside the loop block and executed during each iteration.
  6. Once the count reaches 11, the condition counter <= 10 will be evaluated to False, and the loop will terminate.
  7. The code output will be the numbers 1 to 10

When to use FOR loops | WHILE loops

For Loops: Use for loops when you know the number of iterations in advance and want to process each element in a sequence. They are best suited for iterating over collections and sequences where the length is known.

While Loops: Use while loops when you need to perform a task repeatedly as long as a certain condition holds true. While loops are particularly useful for situations where the number of iterations is uncertain or where you’re waiting for a specific condition to be met.


Close Bitnami banner
Bitnami