Control Structures-While loop

It is essential to exert maximum effort when dealing with repetitive tasks to avoid mistakes. There are several ways to program such repetitive tasks.

In programming, we refer to loops as control structures that repeatedly execute a specific task a certain number of times (or indefinitely). Python provides two types of loops:

  • while loops
  • for… in… loops, which are very powerful

Loops – The while Statement

a = 0
while (a < 7):  # (Don't forget the colon!)
a = a + 1   # (Don't forget the indentation!)
print(a)

The word “while” in English means “when”. The while statement used in the second line tells Python to continuously repeat the following block of code as long as the variable a is less than 7.

Similar to if statements, the while statement begins with a condition. The colon (:) at the end of the line tells Python that a code block follows, which must be indented to the exact same level (using the same number of spaces).

We have now built our first loop, which repeats the indented block of code multiple times. But how does it work?

How the while Loop Works

  • When using a while loop, Python first evaluates the condition inside the parentheses () (the parentheses are optional and were used here for clarity).
  • If the condition is false, Python ignores the block of code and exits the program.
  • If the condition is true, Python executes the block of code, forming a loop. This means:
    • The statement a = a + 1 increases the value of a by 1 (i.e., reassigns a with its previous value + 1).
    • The function print(a) displays the current value of a.
  • After executing these two statements, Python returns to the while statement and checks the condition again:
    • If the condition is still true, the loop continues.
    • If the condition is false, the loop terminates.

In our example, as long as the condition a < 7 remains true, the loop will continue executing.

Notes

  • The variable used in the condition must already exist (meaning it must have been declared and assigned a value, like a = 1).
  • If the condition is false from the start, the loop never runs (the block is skipped).
  • If the condition remains true indefinitely, the loop will run forever (as long as Python is running).
    • To avoid an infinite loop, you must ensure that at least one statement in the loop modifies the variable that controls the condition at the right time so that the condition eventually becomes false.

Infinite Loop Example (Avoid It!):

n = 3
while n < 5:
    print("hello!")

The above loop never ends because the value of n does not change inside the loop.

Generating Tables

Now, let’s slightly modify the first exercise:

a = 0
while a < 12:
    a = a + 1
    print(a, a**2, a**3)

This program prints a list of squares and cubes for numbers from 1 to 12. The output of this program will look like:

1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
11 121 1331
12 144 1728

Note: In the example above, you can see, we can pass multiple arguments to the print() function to display different values on the same line, separated by spaces. Python automatically inserts a space between the displayed elements.

Mathematical Structure: Fibonacci Sequence

The small program below prints the first ten numbers of the Fibonacci sequence. In this sequence, each number is the sum of the two preceding numbers. Try analyzing the program and describe the function of each line.

a, b, c = 1, 1, 1
while c < 11:
    print(b, end=" ")
    a, b, c = b, a + b, c + 1

Output:

1 2 3 5 8 13 21 34 55 89

The Fibonacci sequence is displayed on the same line due to the parameter end=" " in the print() function.

By default, print() automatically moves to the next line after displaying a value. However, by specifying end=" ", we replace the newline with a space, keeping all values on the same line. If you remove end=" ", each number will be printed on a new line instead.

To visualize the loop’s execution, we can write down a table manually, like the one below for the Fibonacci program:

IterationabcFormula Used
Start111Initial values
1st122b = a + b
2nd233b = a + b
3rd354b = a + b
4th585b = a + b

This table tracks how the values of a, b, and c change in each iteration, helping you understand and debug your program in case of a error.

In the next article, we will read about Predefined functions in Python.

No Comments

Leave a Reply