Pharmaceutical company researchers summarized Python control statements

Introduction

Here, we will explain "control statements" for Python beginners. It is supposed to use Python3 series.

Conditional branch

It is used when you want to divide the processing according to the conditions.

if statement

If the conditional expression following ʻif is True, the process is executed. ʻIf the conditional expression: is written, the next line will be indented by 4 spaces.

if_1.py


x = 2
y = 2

if x == y:
    print('x and y are equal.')

In this example, x == y is True, so x and y are equal. It is output as .

Also, if you enter ʻelse, you can describe the processing when the judgment of the conditional expression following ʻif is not True.

if_2.py


x = 2
y = 3

if x == y:
    print('x and y are equal.')
else:
    print('x and y are not equal.')

Furthermore, if you enter ʻelif, you can describe the processing when all the conditional expressions above it are judged as False and the conditional expression following ʻelif is True (ʻelifis Abbreviation for else if`).

if_3.py


x = 2
y = 3

if x == y:
    print('x and y are equal.')
elif x == 2:
    print('x and y are not equal, but x is 2.')
else:
    print('x and y are not equal and x is not 2.')
    
if x == 2 and x != y: #You can also use and in the conditional expression.
    print('x is 2, and x and y are not equal.')
elif x == y or y == 4: #You can also use or in the conditional expression.
    print('x and y are equal, or y is 4.')
else:
    print('other than that.')

if x == 2:
    if y == 3: #It can be nested, but it is not recommended in this case as it reduces readability.
        print('x is 2 and y is 3.')
    elif x == y:
        print('x and y are 2.')
    else:
        print('x is 2, y is neither 2 nor 3.')
elif x == 3:
    print('x is 3.')
else:
    print('x is neither 2 nor 3.')

By the way, there is no switch statement in Python.

Iterative processing

It is used when the same process is repeated multiple times.

for statement

It is used when the same process is repeated a certain number of times. The next line that says for variable in iterable: starts writing with indentation of 4 single-byte spaces.

for_1.py


nums = [1, 2, 3, 4, 5]

for num in nums:
    print(num)

for i, num in enumerate(nums):
    print(i, num)

for i in range(len(nums)): #Not often used.
    print(nums[i])


dict_human = {'height': 200, 'body weight': 100, 'BMI': 25}

for key in dict_human.keys(): #Take out the dictionary key.
    print(key)
    
for value in dict_human.values(): #Fetch the dictionary value.
    print(value)
    
for key, value in dict_human.items(): #Retrieves a dictionary and key value combination.
    print(key, value)


for _ in range(10): #If you do not use the variable after for in the description of the process (you want to specify only the number of executions),'_'But yes.
    print('I ran it.')

You can use break to break the iterative process. In combination with ʻif`, it is often used when processing is stopped when a specific condition is met.

for_2.py


nums = [1, 2, 3, 4, 5]
for num in nums:
    if num == 3:
        break #Processing is stopped when num reaches 3, (only up to 2 is output).
    print(num)

You can use continue to skip iterative processing. This is also often used in combination with ʻif`.

for_3.py


nums = [1, 2, 3, 4, 5]
for num in nums:
    if num == 3:
        continue #Output processing is not performed only when num is 3 (other than 3 is output).
    print(num)

You can use ʻelse` to describe the processing when the processing for for minutes is performed without interruption to the end.

for_4.py


nums = [1, 2, 3, 4, 5]

for num in nums:
    print(num)
else:
    print('The iterative process is finished.')

The above script is the same even if you write it as follows.

for_5.py


nums = [1, 2, 3, 4, 5]

for num in nums:
    print(num)
print('The iterative process is finished.')

You might think that the for statement ʻelse` doesn't make sense, but it certainly doesn't make much sense when used like the script above.

Then, when you can use ʻelse is when you combine it with break. You can describe the processing when the processing of the for statement is performed to the end without interrupting the processing with break`.

for_6.py


nums = [1, 2, 3, 4, 5]

for num in nums:
    if num == 3:
        break
    print(num)
else:
    print('The iterative process is finished.') #Not output.
    
for num in nums:
    if num == 10:
        break
    print(num)
else:
    print('The process is finished.') #It is output.

The above script can be rewritten with flags as below, but it is simpler to use ʻelse`.

for_7.py


nums = [1, 2, 3, 4, 5]
break_flg = False #Set a flag to indicate whether iterative processing has been interrupted.

for num in nums:
    if num == 3:
        break_flg = True
        break
    print(num)
    
if break_flg == False:
    print('The iterative process is finished.')

    
break_flg = False
    
for num in nums:
    if num == 10:
        break_flg = True
        break
    print(num)
    
if break_flg == False:
    print('The iterative process is finished.')

If you skip with continue, it is considered that the processing has been completed to the end, so the ʻelse` clause is executed.

for_8.py


nums = [1, 2, 3, 4, 5]

for num in nums:
    if num == 3:
        continue
    print(num)
else:
    print('The iterative process is finished.')
    
for num in nums:
    if num == 5:
        continue
    print(num)
else:
    print('The iterative process is finished.')

while statement

It is used when iterating only while a certain condition is satisfied. The next line written as while conditional expression: starts writing with indentation of 4 half-width spaces.

while_1.py


num = 1

while num < 5:
    print(num)
    num += 1


num = 1

while num < 5:
    num += 1
    print(num)

Since the processing is executed in order from top to bottom in while, the execution result may change depending on the writing method.

Note that if you forget to write the update of the variable value, the process will be repeated infinitely (infinite loop).

while_2.py


num = 1

# while num < 5:
    # print(num)
    
# while True:
    # print(num)

It's a good idea to use for if the number of iterations is fixed, and while if the number of iterations is not fixed.

Summary

Here, we introduced the conditional branching "if" and the iterative processing "for" and "while" as Python control statements. It's a syntax that can be said to be the center of programming, so it's a good idea to learn it while actually using it.

Reference materials / links

What is the programming language Python? Can it be used for AI and machine learning?

Recommended Posts

Pharmaceutical company researchers summarized Python control statements
Pharmaceutical company researchers summarized Python unit tests
Pharmaceutical company researchers summarized classes in Python
Pharmaceutical company researchers summarized functions in Python
Pharmaceutical company researchers summarized Python exception handling
Pharmaceutical company researchers summarized Python coding standards
Pharmaceutical company researchers summarized variables in Python
Pharmaceutical company researchers summarized SciPy
Pharmaceutical company researchers summarized regular expressions in Python
Pharmaceutical company researchers summarized RDKit
Pharmaceutical company researchers summarized scikit-learn
Pharmaceutical company researchers summarized web scraping using Python
Pharmaceutical company researchers summarized Pandas
Pharmaceutical company researchers summarized file scanning in Python
Pharmaceutical company researchers summarized database operations using Python
Pharmaceutical company researchers summarized NumPy
Pharmaceutical company researchers summarized Matplotlib
Pharmaceutical company researchers summarized Seaborn
Pharmaceutical company researchers summarized Python's comprehensions
Pharmaceutical company researchers have summarized the operators used in Python
Pharmaceutical company researchers summarized Python's data structures
How to install Python for pharmaceutical company researchers
Study from Python Hour2: Control statements
A pharmaceutical company researcher summarized the basic description rules of Python
Install Python Control
Summary of Python articles by pharmaceutical company researcher Yukiya
Python control syntax (memories)