Page Content

Tutorials

What Are The Loops In Python? A Comprehensive Guide

Loops in Python

It is frequently necessary to repeat a set of instructions in programming. A block of code can be run repeatedly with control structures called loops. Iteration is a common term for this repeating execution. The while loop and the for loop are Python’s two main loop types.

Loop

Because it is a condition-controlled loop, the while loop repeats a series of code statements only when a specified condition is met. When it is unknown how many times the code block must repeat, this kind of loop is usually employed. It is occasionally called an indefinite loop.

The while loop’s fundamental grammar is:

# initialization (optional, but often needed for the condition)
while condition:
    # Statements to repeat (loop body)
    # Make sure to change a variable used in the condition
    # so that it eventually becomes False
# Statements after the loop

The while keyword is used at the beginning of the while statement, which is followed by a test condition and a colon (:). The code that must be indented, usually by four spaces, and is repeated is found in the loop body.

For a while statement, the following is the execution flow:

  • Either True or False is the outcome of evaluating the condition.
  • Get out of the while statement and go on to the next sentence following the loop body if the condition is False.
  • The loop body’s sentences should be carried out if the condition is true.
  • Execute the body of the loop, then go back to step 1 and reassess the condition.

Until the condition is true, this process is repeated. To eventually make the condition False and end the loop, the loop body must alter the value of one or more of the variables involved in the condition. The loop is infinite if the condition never turns out to be false.

A basic while loop example that counts from 1 to 5 is shown here:

# Initialization
count = 1
# While loop condition
while count <= 5:
    print(count)
    # Update the variable used in the condition
    count = count + 1 # Or count += 1
print("Loop finished.")

The variable count is initialized to 1 in this instance. If count is less than or equal to five, the loop will continue. Count is incremented by 1 after the current value is printed inside the loop. The loop ends when count <= 5 evaluates to False, which is the result of count becoming 6.

Loop and Iterators

To iterate over the items of a given sequence or other iterable objects, Python for loop is used. Traversal is the term used to describe iterating across a sequence. In contrast to the while loop, the for loop is usually used when processing each item in a collection or when you want to run a loop body a predetermined number of times. Both count-controlled and definite loops are regarded as such.

A for loop’s general structure is as follows:

for iteration variable in sequence:
    # Statements to repeat for each item (loop body)

The for loop starts with the for keyword, then the sequence or iterable object, the in keyword, and an iteration variable (which can be any acceptable variable name). The final colon (:) in the header line. The body of the loop contains indented statements.

The for loop iterates from left to right through the elements in the sequence. Each iteration begins with the iteration variable being assigned to the subsequent item in the sequence, after which the loop body’s statements are run for that item. The loop keeps on until the sequence’s items are all processed.

A variety of sequence types, including strings, lists, and tuples, can be iterated over using Python’s for loop. Any object adhering to the iteration protocol can use it.

The range() function that comes with a for loop is a popular method for counting. A series of integers is produced by the range() function, which the for loop can iterate over.

The syntax for range() is range([start ,] stop [, step]).

  • Stop: Produces a range of numbers from 0 to stop, but not beyond.
  • Numbers are generated from start to stop, but not including stop.
  • Step, stop, and start: Produces figures that increase step by step from start to stop (but not including stop).

Using a string and range(), the following are instances of for loops:

# Iterating over a string
for char in "Python":
    print(char)
# Iterating over a range of numbers (0 to 4)
for i in range(5):
    print(i)
# Iterating over a range with start and stop (2 to 5)
for j in range(2, 6):
    print(j)
# Iterating over a range with start, stop, and step (1 to 9, step 2)
for k in range(1, 10, 2):
    print(k)

Nested Loops

Having one or more loops inside the body of another loop is known as a nested loop. Loops of the same kind can be nestled inside loops, while loops inside for loops, or for loops inside while loops.

There are usually one or more inner loops and an outer loop in nested loops. The inner loop’s complete execution frequency is managed by the outer loop. All repetitions of the inner loop are finished for each and every iteration of the outer loop.

Loop nesting adds complexity to your code, and an excessive number of nested loops can degrade performance. But for many programming jobs, including dealing with two-dimensional data structures or creating patterns, nested loops are required.

A basic pattern is printed using nested for loops in the following example:

# Outer loop
for i in range(3):
    # Inner loop
    for j in range(4):
        # This print statement executes 3 * 4 = 12 times
        print('*', end='') # end='' prevents newline after each asterisk
    # This print statement executes 3 times (once after each inner loop completes)
    print() # Print a newline character

This code shows how the outer loop (for i in range(3):) always iterates over the inner loop (for j in range(4):).

Control statements like break and continue change loop execution. Break can terminate the loop instantly, or continue can skip the current iteration and start the next.

Learning and practicing while loops, for loops (with range() and iteration over sequences), and nested loops can help you design programs that efficiently handle data collections and repetitive tasks.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index