The basics of programming consist of "conditional branching" and "repetition". Use a for statement or while statement to repeat, and use an if statement for conditional branching.
In the sense of repetition, the for statement and while statement are the same, but the difference is that the for statement combines all the conditions related to repetition control into one statement. Therefore, if the initialization, continuation judgment, and variable update process are simple, the for statement that allows you to read everything at a glance is preferred, and conversely, if it is complicated, the while statement is preferred.
table of contents 1 [What is a Python for statement? ](## What is a Python for statement?) 2 [Repeat statement using the range function in the for statement](## Repeat statement using the range function in the for statement) 3 [Conditional branching using for statement and if statement](## Conditional branching using for statement and if statement) 4 [break-continue statement](## break-continue statement) 5 [for-else statement](## for-else statement)
The syntax of the for statement is as follows.
for variable in a collection of data:
processing
if condition:
Process A
Process B
Process C
In principle, the flow of the for statement is to "take out data one by one" from "a collection of data". Various objects can be placed in the "collection of data" part. You can put your own class there if you follow certain rules.
A "variable" is a name for accessing an object retrieved from a collection of data. You can write any name you like here, and the names such as "i, j, k", "index", and "counter", which are often used in the process of "looping 〇 times", are "character strings". Names such as "char" are often used for "extracting one character at a time" and "row" for "extracting a line from a database or text file".
For example, the process of extracting and displaying the character string ‘Hello’ character by character is as follows.
for char in 'Hello':
print(char)
Execution result
H
e
l
l
o
End
First, the "H" in "Hello" is assigned to the variable name char. In print (char), it is initially displayed as "H". Next, "e" is passed to the char variable and displayed by print (char), and then the same processing as e, l, l, o is performed.
String – ‘Python’
List –[‘perl’, ‘python’, ‘php’, ‘ruby’]
Tuple –(‘perl’, ‘python’, ‘php’, ‘ruby’)
Set –{‘perl’, ‘python’, ‘php’, ‘ruby’}
Dictionary –{‘language': ‘Python’, ‘frame_work': ‘Django’}
End
The most common iterative process is "repeat a specified number of times". Python for statements use what is called the "range function".
A sample for statement that repeats 5 times is as follows.
for i in range(5):
print(i)
Execution result
0
1
2
3
4
End
Many people find it a little confusing, but the first i to enter is 0. 0, 1, 2, 3, 4 are displayed in order. If you don't like this, you can do the following:
for i in range(1, 6):
print(i)
Execution result
>
1
2
3
4
5
End
If you loop from 1 to 100, the range function looks like this:
for i in range(1, 101):
print(i)
It is very common to iterate and change the process depending on certain conditions. Let's write a process that repeats from 1 to 10 and displays only when it is a multiple of 3.
It's from 1 to 10, so it's range (1, 11)
for i in range(1, 11):
if i % 3 == 0:
print(i)
Execution result
3
6
9
End
Of course, you can also write elif, else, etc. The function of the if statement does not change even in the for statement.
As with the while loop, breaking the loop with brake and jumping to the next loop with continue are also supported.
The following sample code looks for the string "python" in the list, displays "OK" if it matches, exits the loop, and displays the string otherwise.
strings = ['ruby', 'python', 'perl', 'java', 'c']
for string in strings:
if string == 'python':
print('OK')
break #Since they match, break out
print(string)
Execution result
ruby
OK
End
Since I broke through the loop with break, the following strings are not displayed. If you make something that does the same thing with continue, it will be as follows.
strings = ['ruby', 'python', 'perl', 'java', 'c']
for string in strings:
if string != 'python':
print(string)
continue #Since they do not match, go to the next loop
print('OK')
break
It depends on the process, but continue is not used so often, so if you remember break, there is basically no problem.
Like the while statement, you can use else.
Below is a list of test scores, with no score below 70 being displayed as "passed".
scores = [100, 71, 80, 99, 75] #Passed because there is no less than 70 points
for score in scores:
if score <= 70:
break
else:
print('Pass')
Don't get confused if you remember that this else block only fits if there is no break. This time, there was no break with 70 points or less, so I entered the else block and displayed "Pass". Note that you can enter else without looping even once. In this example, you can pass even if you haven't taken the test (even if the list is empty).
Reference site: [Introduction to Python] How to write repeated statements using for statements
Recommended Posts