Python | Learned about for and while statements


Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

Recently, I have been learning Python.

The following is a brief description of the environment in which Python runs.

  • Windows 10 64bit
  • python 3.9.4
  • PyCharm Community Edition 2021.1 x64

More details can be found in the following article.

In this article on programming in Python, we have tried the basic usage of for and while statements. This article is a reminder of what we learned.

while statement

We learned about for and while statements, but I found the for statement a bit difficult in Python. So, I will start with the while statement.

In addition, you need to know about conditional expressions in while statements. In the beginning, it is good to know how to use conditional expressions with comparison operators. A memorandum on comparison operators can be found in “Learned the comparison operator“.

Basic usage of the while statement

The while statement is used when you want to repeat the process as long as the specified condition is true. The basic syntax is as follows

while [conditional expression]:
    Process to be executed 1
    Process to be executed 2
    Process to be executed 3

The process to be repeated in the while statement is written by indenting the line following the word “while". If there are more than one statement to be executed in the while statement, indent the statement after it. For convenience, we will call the indented line a block. The general process is as follows.

  1. [conditional expression] is evaluated.
    1. If the result is True, the block is processed in order.
    2. If the result is false, exit the loop.
  2. Return to the beginning (evaluation of [conditional expression]).

The following is a simple sample program.

i = 0
while i < 3:
    i += 1
Execution results

In the block of while statement in the sample program above, the value of variable i is added by 1 at the end. When the value of variable i becomes 3, the result of the conditional expression i < 3 becomes false. At that time, the block will not be executed.

In the above block, if you remove the last process “i += 1", the while statement will not finish. This is because the result of the conditional expression i < 3 will always be True. In the while statement, you need to be careful because the processing contents may become infinite loop.

If such a situation occurs due to a programming error, you will be forced to terminate the program; PyCharm Community Edition has a button to stop the program.

The following is a sample program to practice using the stop button to stop the process.

import time

i = 0
while i < 10:
    i += 1

The above program will add the value of variable i every second, and the process will end when the value of variable i reaches 10. Since the program runs for at least 10 seconds, it is a good practice to press the stop button before the process is over.

The area shown in the image above is the stop button. Clicking this button will terminate the program.

In the conditional expression of the sample program above, in addition to determining the integer value of the variable i, there is another way to use the characters entered, as shown below.

tax_rate = 0.08

c = 'y'
while c == 'y':
    price = int(input('price: '))
    print('The tax included price for {0} is {1}.'.format(price, round(price * (1 + tax_rate))))

    c = input('To continue, enter "y":')

In this sample program, when you enter a price, the program will output the price including tax. At the end of the while statement block, the program asks the user to enter a character, which is used to determine whether to execute the next iteration.

Since the result of price * (1 + tax_rate) is of type float, we use the built-in function round(). This function rounds off the value of the first argument. If the second argument is omitted, it returns the integer closest to the input value.

The following is an example of the execution result. In the character input, “y" is input the first time, and anything other than “y" is input the second time.

Execution results
price: 100
The tax included price for 100 is 108.
To continue, enter "y":y
price: 200
The tax included price for 200 is 216.
To continue, enter "y":a

There are also uses of the while statement where the number of repetitions is indefinite, as shown above.

for statement

Another syntax for specifying repetitive operations is the for statement.

Repeat the process 10 times with a for statement

The for statement can be used to iterate. The syntax of the Python for statement itself will be described later. Here is how to describe the process when it is repeated 10 times.

for n in range(10):
Execution results

The above sample program repeats the process of outputting the values from 0 to 9 for the variable n. When I ran this program for the first time, I vaguely felt that the result of range(10) was something like a sequence of numbers from 0 to 9.

Python defines a built-in type called range. range(10) means that we are passing the integer 10 to the constructor of type range. The generated object can then be passed to list().

In the following program, list() is used to output the contents of range(10).

values = range(10)
Execution results
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We now know that the result of list(values) is a sequence of numbers from 0 to 9.

The syntax of the for statement is roughly in the following form

for variable in [list, etc.]:
    Process to be executed 1
    Process to be executed 2
    Process to be executed 3

The part that says [list, etc.] seems to be more accurately describing an object that will generate an iterator object. As a beginner, it is difficult for me to understand, so I decided that knowing that I can use range types and lists is enough for now.

The variable stores the elements of the object written in the [list, etc.] section. In the case of a list, the first iteration stores the first element of the list in the variable, and the second iteration stores the second element of the list in the variable.

Using lists in for statements

In the following sample program, we have tried a for statement using list.

values = [99, 'abc', 100, 0.123]
for value in values:
    print('{0}...{1}'.format(value, type(value)))
Execution results

The elements of values in the sample program above include integers, strings, and decimals. Each is stored in the variable value in an iterative process. The type of the variable depends on the stored value.

Index of the list

You can use list in a for statement, but to use the index of the list in an iterative process, use the built-in function enumerate().

The following is a sample program that just displays the value of a variable.

values = [99, 'abc', 100, 0.123]

for i, value in enumerate(values):
    print(f'{i=}, {value=}')
Execution results
i=0, value=99
i=1, value='abc'
i=2, value=100
i=3, value=0.123

The variable i above stores integer values in order from 0. As a beginner, you should remember the above as a type.

The following sample program shows a little more about the objects returned by the enumerate() function.

values = [99, 'abc', 100, 0.123]

l = list(enumerate(values))
Execution results
<enumerate object at 0x000002104F5F6940>
[(0, 99), (1, 'abc'), (2, 100), (3, 0.123)]

The enumerate() function returns an enumerate object. You can specify it as an argument to the list() function. It turns out that the output result is something like a double array. (I won’t go into the details here).

That’s all we have learned so far, and we will write about how to apply the for statement in another article.

That’s all. I hope this is helpful to you.