[Python] Chapter 05-01 Control syntax (comparison operator and conditional branching)

[Python] Chapter 05-01 Comparison Operators and Conditional Branches

From this chapter you will learn about control syntax. The programs you have written so far are basically processed in order from the top and executed in order.

However, as in our lives, we usually make decisions while making decisions. For example, "go out if the weather is sunny" and "spend indoors if the weather is rainy".

You can select the process to be executed by making the same judgment in a computer program. However, you need to learn a new operator called the comparison operator to specify the condition. Comparison operators are not that difficult, but the notation is different from mathematics, so keep that in mind.

Comparison operator ~ Condition description ~

First, I will explain the important comparison operators in conditional branching. For example, the following formulas are, of course, equal.

5 = 2 + 3

To check if this is equal in a Python program, write: Enter the following code in the ** Python Console **. In addition, please write two consecutive ** = (equal). ** **

>>> 5 == 2 + 3
True

I'm trying to determine if adding 2 and 3 gives 5. Naturally, it will be ** True **. In addition, although it is described as ** "==" **, this is a comparison operator. Judgment is made by comparing the left side and the right side. Please note that if you set ** "=" (equal) **, it will be an assignment. (*) </ font> In Python, "==" means equality in the comparison operator, but please note that it differs depending on the program language.

Now, let's dare to enter different values. Enter the following code in the ** Python Console **.

>>> 5 == 1 + 3
False

I'm trying to determine if the result of adding 1 and 3 is 5. Naturally, it will be ** False **.

There are other types of comparison operators as follows.

Comparison operator meaning Example Meaning of example
== equal x == 5 Are x and 5 equal??
!= Not equal x != 5 Are x and 5 not equal??
> Greater x > 5 Is x greater than 5?
>= that's all x >= 5 Is x 5 or more??
< Less than (less than) x < 5 Is x less than 5?
<= Less than x <= 5 Is x 5 or less??

The following is an execution example. Let's actually substitute a different value and try it.

>>> 5 == 5
True
>>> 5 != 5
False
>>> 5 != 4
True
>>> 5 > 4
True
>>> 5 >= 5
True
>>> 5 > 5
False

You can also compare character strings and lists.

>>> 'book' == 'book'
True
>>> 'book' != 'book'
False
>>> L1 = [1, 2, 3]
>>> L2 = [1, 2, 3]
>>> L1 == L2
True

Conditional branch (if statement)

Here, we will touch on conditional branching. To write a conditional branch, write a ** if statement **.

Grammatically, it is described as follows.

if condition:
Processing to be executed when the conditions are met

This "when the condition is met" means when the result of the comparison operator (that is, the condition) is ** True **.

Don't forget ** ":" ** (colon) after the conditional expression. Without this, an error will occur.

Also, before the "process to be executed when the conditions are met", the "Tab key" is ** indented **. Don't forget this too. Without this, the contents of the ** if statement ** cannot be understood. (Details are described below)

Writing grammatically makes it difficult, so I will explain it while actually writing the program. The programs described this time are as follows. Enter an integer value from the keyboard, and if it is positive, create a program that states "A positive value has been entered". </ font>

First, I would like to express the conditions with a ** flowchart (flow chart) **. Drawing a flowchart makes it easier for anyone to understand the contents of the program.

image.png

Let's create a program based on this. I'm going to create a program, but this time I'll create a folder and a .py file to input the program into the editor for the first time in a while. For this file, create a chap05 </ font> folder, and create a file called 05-01-01.py </ font> in it. To do. If you forget how to create it, please check it at "Chapter 01-03".

05-01-01.py


#Input an integer value. If this is left as it is, it will be a character string, so convert it to a numerical value with the int function.
n = int(input('Please enter an integer value:'))

#Print with the print function if the value is positive, that is, if n is greater than 0
if n > 0:
    print('A positive integer value has been entered')

After writing the program, let's execute it.

[Execution result] </ font> Enter an integer value: 5 </ font> A positive integer value has been entered

** "5> 0" ** is judged at the place of ** n> 0 ** in if. Of course, since it is ** True **, the inside of the if statement is executed.

About indentation

Earlier, I said that the content of the if statement should be indented. Let's dig a little deeper into this. Please add the following code.

05-01-01.py


#Input an integer value. If this is left as it is, it will be a character string, so convert it to a numerical value with the int function.
n = int(input('Please enter an integer value:'))

#Print with the print function if the value is positive, that is, if n is greater than 0
if n > 0:
    print('A positive integer value has been entered')
    print(f'Now you{n}I entered.')

I will write another code. Create a file called 05-01-02.py </ font> in the chap05 </ font> folder. The only difference is that you haven't indented the last output.

05-01-02.py


#Input an integer value. If this is left as it is, it will be a character string, so convert it to a numerical value with the int function.
n = int(input('Please enter an integer value:'))

#Print with the print function if the value is positive, that is, if n is greater than 0
if n > 0:
    print('A positive integer value has been entered')
print(f'Now you{n}I entered.')

Please execute each. In that case, please enter a negative value **.


05-01-01.py Execution result

[Execution result] </ font> Please enter an integer value: -1 </ font>


05-01-02.py Execution result

[Execution result] </ font> Please enter an integer value: -1 </ font> Now you have entered -1.

Did you see the difference? First, since the entered numerical value is ** n = -1 **, at ** n> 0 **, ** -1> 0 ** and ** False **, so the inside of the if statement is processed. Will not be. Up to this point, it is common to both programs.

In 05-01-01.py </ font>, the two lines in the if statement are indented, so they are treated as processing in the if statement **, this time. Has not been processed. In 05-01-02.py </ font>, one of them is not indented, so the if statement ends and ** is executed as a process outside the if statement **. You will be there.

It is difficult to write in letters, so the difference is as follows when drawn in a flowchart. image.png

Conditional branch (if-else statement)

In the programs I have written so far, when a positive value is input, "A positive integer value has been input" is output. But what if a negative value is entered? I actually typed -1 earlier, but it didn't say "a negative integer value was entered".

In other words, nothing is written about what to do if the conditions are not met. If you want to write such a condition, use ** else **. The syntax is as follows.

if condition:
Processing to be executed when the conditions are met
else:
What happens when the conditions are not met

Actually, write the program as follows. Create a file 05-01-03.py </ font> in the chap05 </ font> folder and enter the following code Please give me.

05-01-03.py


#Input an integer value. If this is left as it is, it will be a character string, so convert it to a numerical value with the int function.
n = int(input('Please enter an integer value:'))

#Print with the print function if the value is positive, that is, if n is greater than 0
if n > 0:
    print('A positive integer value has been entered')
else:  ##Output with the following print function when the above conditions are not met
    print('Negative integer value entered')
print(f'Now you{n}I entered.')


05-01-03.py Execution result

[Execution result] </ font> Please enter an integer value: -1 </ font> Negative integer value entered Now you have entered -1.

To explain, I entered ** n = -1 ** as the input value this time. Therefore, in the condition, **-1> 0 **, so ** False **, and the condition is not satisfied. Therefore, the ** else ** side is executed, and "A negative integer value has been entered" is output.

Conditional branch (if-elif-else statement)

Now, try again in this state and enter ** 0 ** as the input value. Then the result is as follows.


05-01-03.py Execution result

[Execution result] </ font> Enter an integer value: 0 </ font> Negative integer value entered Now you have entered 0.

Even though ** 0 ** is neither a positive number nor a negative number, "A negative integer value has been entered" is output. When ** 0 ** is input, try to improve it so that "0 has been input" is output.

But then there are three branches. How do you express it? To solve this, use the statement ** elif **. The syntax is as follows.

if condition 1:
Process executed when condition 1 is met
elif condition 2:
Process executed when condition 2 is not satisfied without satisfying condition 1
else:
Processing to be executed when condition 2 is not met

Let's actually write the program. Create a file 05-01-04.py </ font> in the chap05 </ font> folder and enter the following code. Please give me.

05-01-04.py


#Input an integer value. If this is left as it is, it will be a character string, so convert it to a numerical value with the int function.
n = int(input('Please enter an integer value:'))

#Print with the print function if the value is positive, that is, if n is greater than 0
if n > 0:
    print('A positive integer value has been entered')
elif n < 0:  ##Output with print function when n is less than 0
    print('Negative integer value entered')
else:  ##n>But n<When it is not 0 (that is, when it is 0)
    print('0 was entered')
print(f'Now you{n}I entered.')

Let's express it with a flowchart here. I think it is as follows. Let's follow the process by comparing the program and the flowchart. image.png

Practice problem

We have prepared exercises. Please try to solve it. In addition, please use the file name specified in [] and create it in chap05 </ font>. You can specify any variable name you like. [05-01-p1.py] [1] Create a program that determines whether the entered integer is even or odd. (Hint: Even numbers are divided by 2 to get 0, and odd numbers are divided by 2 to get 1).
05-01-p1.py execution result

[Execution result] </ font> Please enter an integer: 1 </ font> Is odd

[05-01-p2.py] [2] Read a positive integer value and divide it by 3, "the value is divisible by 3", "the value is more than 1 when divided by 3", "the value is divided by 3" Create a program that displays one of "and 2 surplus".
05-01-p2.py Execution result
> [Execution result] Please enter an integer: 256 That value is more than 1 when divided by 3

Finally

Today I learned about if statements, which are important for programming. If statements often appear as a matter of course for programs to be learned in the future. Every program has a condition judgment, so be sure to remember it.

Return to [Table of Contents Link]

Recommended Posts