Reference site: [[Introduction to Python] How to use while statement (repetitive processing)] (http://programming-study.com/technology/python-while/)
Not limited to Python, the basics of programming are "conditional branching" and "loop processing". There are two types of conditional branching in Python: if statements, and loop processing: "for statements" and "while statements". This time, I will introduce the while statement.
The while statement is mainly used for processing such as "infinite loop" and "repeat for a certain condition".
table of contents 1 [How to write a while statement](## How to write a while statement) 2 [Try using a while statement](## Try using a while statement) 3 [Try using break](Try using ## break)
while conditional expression:
Processing you want to repeat
I will write it as.
As the name suggests, write the condition in the "conditional expression" part. While the conditional expression is evaluated as True, it will endlessly "process what you want to repeat".
For example, in the following cases
while conditional expression:
Process A
Process B
In this case, process A is repeated, and when the conditional expression becomes False, the repetition ends and the process moves to process B. It is only the while block that is repeated.
Let's create a while loop that displays 1 to 5.
index = 1
while index <= 5:
print(index)
index += 1
print("End")
Execution result
1
2
3
4
5
End
The processing flow is as follows.
In the first line index = 1, substitute 1 for the variable index
The second line while index <= 5: means that the while block is executed while the index is 5 or less (including when it is 5). The current index is 1, so it is 5 or less. Move on to the third line.
Line 3 print (index) Displays the index. Currently, the index contains 1, so 1 is displayed.
Line 4 Add 1 to the index variable. At this point, the value of the index variable is 2.
Go to line 2 The index variable is still 2. Since it is 5 or less, go to the third line again
After this, index + = 1 will continue until it reaches 6.
The second line index is 6, not less than 5. So, instead of going to the 3rd line, jump to the 5th line. Try using break
In a while loop, you can break out of the loop by using a break statement. Let's modify the previous example and do the following.
index = 1
while index <= 5:
print(index)
index += 1
break
print("End")
It is the same up to index + = 1 on the 4th line, but when you reach the break on the 5th line, it immediately breaks out of the loop and moves to the 6th line. So the result is:
Execution result
1
End
up until this point
while conditional expression:
Process A
It is written as, but by using this break
while True:
if conditional expression:
break
Process A
You will be able to write. While doing an infinite loop with while True, break with the if statement inside and exit the loop. This method is also often used, so be sure to remember it.
Recommended Posts