[Python of Hikari-] Chapter 05-08 Control syntax (while statement-another iterative syntax-)

[Python] Chapter 05-08 while Statement-Another Iterative Syntax-

First, take a look at the program below (no need to write a program)

for i in range(10):
    print(i, end=' ')

print('Processing Exit')

It uses a for statement to output values from 0 to 9. Until now, it was described as ** for statement **, but this time, let's touch on expressing the above program with ** while statement **.

How to write a while statement

Generally, the while statement is written as follows.

while conditional expression:
Contents of processing

The conditions are such as ** i <10 ** and ** i == 0 **, which I wrote in the if statement. Let's actually express the above for statement program using a while statement. In chap05 </ font>, create a file with the file name 05-08-01.py </ font>, and the following code Please write.

05-08-01.py


i = 0  ##Initialize the value of i with 0

while i < 10:  ##Process when i is less than 10
    print(i, end=' ')
    i+=1  ##Add 1 to i

print('Processing Exit')


05-08-01.py Execution result

[Execution result] </ font> 0 1 2 3 4 5 6 7 8 9 Finished processing

It looks like the program is a little longer than the for statement. Let's follow the process.

First, in the case of ** while statement **, initialization is performed with ** i = 0 ** when performing iterative processing. In other words, we need to decide what to do with the first value. In the ** for statement **, the 0 part of range (0, 10) is the start, so the 0 of the start is decided. Also, in the case of a while statement, ** i = 0 ** can be set to ** the number of repetitions **.

Next, let's go into the contents of the while statement.

** [1st loop] </ font> ** With ** while i <10: **, the process is repeated when the conditional expression is ** True **. Now, since ** i = 0 **, the conditional expression becomes ** 0 <10 **, and ** True **, so the while statement processing starts.

Then, the value of ** i ** (** i = 0 **) is output, and then ** i + = 1 **. If this ** i + = 1 ** is not done, the condition judgment when ** [2nd loop] </ font> ** will be the same ** 0 < It becomes 10 **, and it becomes an infinite loop, and you cannot get out of the while statement forever. So don't forget to add i by 1 with ** i + = 1 **. (At this point, ** i = 1 **.)

** [2nd loop] </ font> ** Now, since ** i = 1 **, the conditional expression becomes ** 1 <10 ** and ** True **, so the while statement processing starts.

Then, the value of ** i ** (** i = 1 **) is output, and ** i + = 1 ** is set. (At this point, ** i = 2 **.)

<font color = # 0cc> <Repeat the while statement while the condition is i <10. > </ font>

** [10th loop] </ font> ** Now, since ** i = 9 **, the conditional expression becomes ** 9 <10 ** and ** True **, so the while statement processing starts.

Then, the value of ** i ** (** i = 9 **) is output, and ** i + = 1 ** is set. (At this point, ** i = 10 **.)

** [11th loop] </ font> ** Now, since ** i = 10 **, the conditional expression becomes ** 10 <10 **, ** False **, and exits from the while statement.

Then, ** print ('end of processing') **, which is outside the while statement, is output.

This is shown in the flowchart below.

image.png

Calculate the sum using a while statement

As mentioned in the for statement, for example, to find the sum of even numbers with an integer between 1 and 100, we calculated it as follows. (No need to write a program)

sum = 0
for i in range(1, 101):
    if i % 2 == 0:
        sum += i

print(f'Sum:{sum}')


Execution result

Sum: 2550

I don't think it is necessary to explain in particular, but it is judged whether it is an even number at the if statement, and if ** i ** is an even number, it is added.

Let's express this with a ** while statement ** instead of a for statement. Create a file with the file name 05-08-02.py </ font> in chap05 </ font>, and use the following code Please write.

05-08-02.py


sum = 0
i = 1

while i <= 100:
    if i % 2 == 0:
        sum += i  ##Calculate the sum here
    
    i += 1 ##Increase the value of i by 1
print(f'Sum:{sum}')

First, to find the sum, initializing the value of ** sum ** is the same as in the for statement. If sum is not set to 0, it will not be calculated correctly.

Then, ** 1 ** is substituted for ** i **, and the condition of the while statement is judged. While ** i ** is 100 or less, the condition of the while statement becomes ** True **, and the process is repeated, so addition is performed during that time.

** [1st loop] </ font> ** Since ** i = 1 **, the condition of the if statement is ** False **, the addition process to sum is not performed, and the process in the if statement is skipped. And don't forget to add 1 to ** i **. If you don't do this, you'll end up in an infinite loop, as mentioned above. (At this point ** sum = 0, i = 2 **)

** [2nd loop] </ font> ** Since ** i = 2 **, the condition of the if statement is ** True **, and the addition process to sum is performed in the if statement. Then add 1 to i to get i = 3. (At this point ** sum = 2, i = 3 **)

** [3rd loop] </ font> ** Since ** i = 3 **, the condition of the if statement is ** False **, the addition process to sum is not performed, and the process in the if statement is skipped. Then add 1 to i to get i = 4. (At this point ** sum = 2, i = 4 **)

<font color = # 0cc> <Repeat the while statement while the condition is i <= 100. > </ font>

** [100th loop] </ font> ** Since ** i = 100 **, the condition of the if statement is ** True **, and the addition process to sum is performed in the if statement. Then add 1 to i to get i = 101. (At this point ** sum = 2550, i = 101 **)

** [101st loop] </ font> ** Then, the condition of the while statement is ** 101 <= 100 **, and ** False **, so the while statement is exited.

And finally, the print function outputs the sum value.

Practice problem

We have prepared exercises. Please try to solve it. In addition, please use the file name specified in [] and create it in chap05 </ font>. You can specify any variable name you like. [05-08-p1.py] [1] Create a program that calculates the sum of odd numbers of integers from 1 to 100 using the while statement. The result is 2500.

[05-08-p2.py] [2] Create a program that calculates the average of the elements in the list ** ls = [3, 5, 4, 10, 7, 8] ** using the while statement. The result is 6.166666666666667. (Hint: ** ls [0] ** can retrieve elements such as ** 3 **, ** ls [1] ** can retrieve elements such as ** 5 **…, that is, ** ls [i] * You can retrieve the element as *. You can also get the length of the list with ** len (ls) **, so you can repeat the process between those lengths.) [05-08-p3.py] Create the program of [3] and [2] using ** for statement **.

Finally

I mentioned the while statement, but the program is a little longer than the for statement. However, what I'm doing is the same, so I think it was easy to understand. Next time, I would like to briefly explain the techniques often used in while statements.

Return to [Table of Contents Link]

Recommended Posts