[Introduction to Python] How to write repetitive statements using for statements

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)

What is a Python for 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

Iterative statement using the range function in the for statement

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)

Conditional branching using for and if statements

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.

break-continue 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.

for-else statement

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

[Introduction to Python] How to write repetitive statements using for statements
[Introduction to Python] How to write conditional branches using if statements
[Introduction to Python] How to use while statements (repetitive processing)
Introduction to Python For, While
[Introduction to Python] How to stop the loop using break?
How to write a Python class
[Introduction to Python] How to parse JSON
[TouchDesigner] Tips for for statements using python
An introduction to Python for non-engineers
[Python] Introduction to graph creation using coronavirus data [For beginners]
[Introduction to Python] How to use class in Python?
How to write Python document comments (Docstrings)
How to use "deque" for Python data
An introduction to Python for machine learning
How to write Ruby to_s in Python
An introduction to Python for C programmers
[Introduction to Python] How to write a character string with the format function
[Introduction to Udemy Python3 + Application] 23. How to use tuples
How to install Python for pharmaceutical company researchers
[Introduction to Python] How to handle JSON format data
How to write a ShellScript Bash for statement
[Introduction to Udemy Python3 + Application] 43. for else statement
Introduction to Programming (Python) TA Tendency for beginners
How to make Python faster for beginners [numpy]
Understand Python for Pepper development. -Introduction to Python Box-
How to install Python
How to install python
Introduction to Python language
Introduction to OpenCV (python)-(2)
How to build an environment for using multiple versions of Python on Mac
[Introduction to Python] How to get the index of data with a for statement
[BigQuery] How to use BigQuery API for Python -Table creation-
[For beginners] How to use say command in python!
How to write a GUI using the maya command
How to convert Python # type for Python super beginners: str
How to write string concatenation in multiple lines in Python
[For beginners] How to study Python3 data analysis exam
[Introduction to Python] How to iterate with the range function?
How to run python in virtual space (for MacOS)
How to auto-submit Microsoft Forms using python (Mac version)
How to write a list / dictionary type of Python3
How to make a Python package using VS Code
[Python] How to write a docstring that conforms to PEP8
Write data to KINTONE using the Python requests module
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
For those who want to write Python with vim
[Introduction to Udemy Python3 + Application] 30. How to use the set
How to retrieve multiple arrays using slice in python.
Python # How to check type and type for super beginners
How to execute a command using subprocess in Python
How to write faster when using numpy like deque
Compare how to write processing for lists by language
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
[Python] How to write type annotations for Callable objects treated as variables and arguments
[2020.8 latest] How to install Python
How to install Python [Windows]
python3: How to use bottle (2)
XPath Basics (2) -How to write XPath
[Python] How to use list 1
How to update Python Tkinter to 8.6
Post to Twitter using Python