The for and while Statements
General Form of while Loop
Just like the
for statement, the
while statement is
iterative and controls a set of instructions.
The general form is as follows:
while true_logical_expression:
subordinate_instructions
The execution principle is:
Step 1. Evaluate the logical expression. If it evaluates to
True, proceed to
Step 2, otherwise the execution of the statement ends.
Step 2. Execute the set of instructions, then return to
Step 1.
EXAMPLE
We read a natural number, stored in
a. Calculate the sum of the first
a natural numbers.
DETAILS
The initial value of the variable
i is
1. As long as
i is less than or equal to the input
a, the
compound statement (subordinate to the
while statement) is executed.
This includes the statement where the value of
i is added to the value stored in
total and the statement where
1 is added to the value
stored in
i (i.e., it is
incremented).
Example for a = 5:
|
Execute the simulation
|
Once again,
pay attention to the indentation of the subordinate instructions...
NOTE
It is recommended to use the
while statement when
two conditions are met simultaneously:
• the set of instructions is executed (as many times as necessary) only if a certain condition is met;
• at the moment of entering the repetitive sequence, it is not known how many times it will be executed.
In the case of the problem above, we could have also used
for:
a = int(input("a="))
suma = 0
for i in range(1, a + 1):
suma += i
print("The sum is", suma)
The call
range(a + 1) was another option, but is it necessary to add the first value,
0?
It would have been
an extra step... so
we need to be optimal!