Python basic course (9 iterations)

Iterative processing

Up to the last time, I explained "sequential / branch" out of "sequential / branch / iteration". This time, I will explain "repetition". "Repeat" means "do the same process multiple times" It can be expressed, but different values can be used for the same process, so Strictly speaking, they are not the same process.

for loop

range Use ** for i in range () ** if you want to repeat it any number of times.

for_explain1.py


for i in range(5):
   print("{0}".format(i))

The variable i is called a "loop counter" in the program. This program outputs a loop counter, but the execution result is as follows. 0 1 2 3 4

By writing range (X), the value of the loop counter stores 0 to X-1, and iterates X times. The value of the loop counter can be used in the processing of the program.

You can set the start value of the loop counter by writing range (X, Y). The value of the loop counter stores X to Y-1, and iterates Y-X times.

for_explain2.py


for i in range(1,10):
   print("{0}".format(i))

1 2 3 4 5 6 7 8 9 The output result will be as above.

enumurate In many cases, you want to get the elements of the list one by one and process each element individually. In this case, use enumurate.

for_explain3.py


a = ["a","b","c","d","e"]
for idx,elem in enumerate(a):
   print("{0} = {1}".format(idx,elem))

0 = a 1 = b 2 = c 3 = d 4 = e The output result will be as above. Two variables can be set after for. The first variable becomes the loop counter (idx in the above program) The latter variable becomes the element (elem in the above program) corresponding to the loop counter in the list.

for_explain4.py


a = ["a","b","c","d","e"]
for idx in enumerate(a):
   print("{0}".format(idx))

(0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e') If only one variable is set after for, the variable will contain the loop counter and the corresponding element.

while loop

While the for loop "repeats a fixed number of times", the while loop It is used when "Repeat while satisfying specific conditions".

while_explain.py


a = ["ok","ok","ok","ng","ok"]
i = 0
while a[i] == 'ok':
    print("a[{0}] is ok".format(i))
    i = i + 1

The output result is as follows. a[0] is ok a[1] is ok a[2] is ok At the beginning of the iterative process, it is determined whether a [i] is "ok", and if it is False, the iterative process ends. After a [3], it will not be processed.

When using a while loop, be sure to change the loop counter so that it does not become an infinite loop. However, pay attention to the indentation of the loop counter at this time. The program below is the wrong program.

while_explain_IL.py


a = ["ok","ok","ok","ng","ok"]
i = 0
while a[i] == 'ok':
    print("a[{0}] is ok".format(i))
i = i + 1

Indentation is invalid (i = i + 1 is not set in the while loop) Since i does not change from 0 in the while loop, an infinite loop occurs.

break and continue

The process of "ending the iterative process" is break, and the process of "ending this iteration and starting the next iterative process" is continue. You can use either for loop or while loop.

break_continue_explain.py


i = 0
while i < 10:
    i = i + 1
    if i < 3:
        continue
    print("i is {0}".format(i))
    if i == 5:
        break

print("final i is {0}".format(i))

The output result is as follows. i is 3 i is 4 i is 5 final i is 5 In the program, continue and break have the following meanings.

if i < 3:   continue

"If i is less than 3, perform the next iterative process without performing subsequent processes." Therefore, if the value of i is 0, 1, or 2, no value will be output on the screen.

if i == 5:   break Means "If i is 5, the iterative process ends", so the last output i is 5.

Else in a loop

If you write the else used in if at the end of the loop statement, you can use it as "processing when the loop ends". You can use either for loop or while loop.

loop_else.py


for i in range(3):
    print("{0}".format(i))
else:
    print("for loop done")

while i < 5:
    i = i + 1
    print("{0}".format(i))
else:
    print("while loop done")

The execution result is as follows. 0 1 2 for loop done 3 4 5 while loop done

However, the following program returns the same execution result.

loop_else2.py


for i in range(3):
    print("{0}".format(i))

print("for loop done")

while i < 5:
    i = i + 1
    print("{0}".format(i))

print("while loop done")

Some programmers who actually use Python on a daily basis don't use else in loops.

Next: Python basic course (10 comprehension)

Recommended Posts

Python basic course (9 iterations)
Python basic course (12 functions)
Python Basic Course (7 Dictionary)
Python basic course (2 Python installation)
Python Basic Course (11 exceptions)
Python basic course (6 sets)
Python Basic Course (Introduction)
Python basic course (13 classes)
Python basic course (8 branches)
Python Basic Course (3 Python Execution)
Basic Python 3 grammar (some Python iterations)
Python basic course (10 inclusion notation)
Python Basic Course (5 List Tuples)
Python Basic Course (1 What is Python)
Python Basic Course (14 Modules and Packages)
Basic Python writing
Python3 basic grammar
RF Python Basic_02
Python Basic Course (at the end of 15)
Python basic course (4 numeric type / character string type)
Python I'm also basic
Python basic grammar / algorithm
[python] class basic methods
Python3 cheat sheet (basic)
Python basic grammar (miscellaneous)
Python basic memorandum part 2
python basic on windows ②
Python basic memo --Part 2
Basic Python command memo
Python basic grammar note (4)
Python basic grammar note (3)
Basic knowledge of Python
Python basic grammar memo
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic if statement
Python Basic --Pandas, Numpy-
Python application: Pandas Part 1: Basic
Refactoring Learned in Python (Basic)
BASIC authentication with Python bottle
Python basic dict sort order
[Python] Using OpenCV with Python (Basic)
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Python basics: conditions and iterations
Basic Python grammar for beginners
[Python] [SQLite3] Operate SQLite with Python (Basic)
Basic usage of Python f-string
I learned Python basic grammar
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
Java and Python basic grammar comparison
Python
Scraping with Selenium in Python (Basic)
Python course for data science_useful techniques
[Python] Basic knowledge used in AtCoder
I took Progete's Python Learning Course I
1. Statistics learned with Python 1-1. Basic statistics (Pandas)