Learned the if statement (if, elif, else)

2021年6月5日

Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

Recently, I have been learning Python.

The following is a brief description of the environment in which Python runs.

  • Windows 10 64bit
  • python 3.9.4
  • PyCharm Community Edition 2021.1 x64

More details can be found in the following article.

In this article, we have tried the basic usage of the if statement (if, elif, else) for programming in Python. This article is a reminder of what we learned.

Sponsored Links

the if statement

For example, “If the score is 80 or higher, print the word Pass" is a conditional branching process, which in Python can be implemented with an if statement as follows.

Source
score = int(input('score: '))

if score >= 80:
    print('Pass’)

print('End’)

The built-in function input() in the first line is a function that waits for a value to be input from the console. The following are the results when 80 is entered and when 79 is entered.

The result of entering 80
score: 80
Pass
End
The result of entering 79
score: 79
End

In the above example, if 80 is entered, the text Pass is output; if 79 is entered, no text is output. As shown above, the if statement can be used to determine the value and branch the process.

The basic syntax of the if statement is as follows

Source
if [conditional expression]:
    [process to be executed 1]
    [process to be executed 2]
    [process to be executed 3]
    .
    .
    .

The process we want to execute when the conditional expression is True is indented by one. The above indented sequence of statements is called a suite in the Python 3.9.4 documentation.

I think the comparison operator is often used in conditional expressions. In my previous article “Learned the comparison operator" contains a reminder of what we learned.

Boolean operation

Suppose we are asked to enter two scores. Then, if we want to determine if the two scores are both above 80, we can use the boolean operator.

The following sample program will output Pass if the two scores are both 80 or higher.

Source
score1 = int(input('score1: '))
score2 = int(input('score2: '))

if score1 >= 80 and score2 >= 80:
    print('Pass’)

print('End’)
Execution results
score1: 80
score2: 80
Pass
End
Execution results
score1: 80
score2: 79
End

For the boolean operation between the two conditions A and B, we can use the following operator.

Expression Result
A and B True if both A and B are true, false otherwise.
A or B True if at least one of A and B is True; otherwise False.

In the following sample program, we actually set True/False for A and B, and output the results of the “and" and “or" operations.

Source
print('{:>10}, {:>10}, {:>10}, {:>10}’
      .format('A’, 'B’, 'A and B’, 'A or B’))

A = True
B = True
print('{:>10}, {:>10}, {:>10}, {:>10}’
      .format(str(A), str(B), str(A and B), str(A or B)))

A = True
B = False
print('{:>10}, {:>10}, {:>10}, {:>10}’
      .format(str(A), str(B), str(A and B), str(A or B)))

A = False
B = True
print('{:>10}, {:>10}, {:>10}, {:>10}’
      .format(str(A), str(B), str(A and B), str(A or B)))

A = False
B = False
print('{:>10}, {:>10}, {:>10}, {:>10}’
      .format(str(A), str(B), str(A and B), str(A or B)))
Execution results
A,          B,    A and B,     A or B
      True,       True,       True,       True
      True,      False,      False,       True
     False,       True,      False,       True
     False,      False,      False,      False

Note that the above sample program uses the built-in function str(). If this function is not used, the output would be 1/0 instead of True/False.

Source
print('{:>10}, {:>10}, {:>10}, {:>10}’
      .format('A’, 'B’, 'A and B’, 'A or B’))

A = True
B = False
print('{:>10}, {:>10}, {:>10}, {:>10}’
      .format(A, B, A and B, A or B))
Execution results
A,          B,    A and B,     A or B
         1,          0,          0,          1

If you want to get the logical negation of condition A, there is the following operator NOT.

Expression Result
not A False if A is true; otherwise, true.

The following sample program outputs the result of not A.

Source
print('{:>10}, {:>10}’
      .format('A’, 'not A’))

A = True
print('{:>10}, {:>10}’
      .format(str(A), str(not A)))

A = False
print('{:>10}, {:>10}’
      .format(str(A), str(not A)))
Execution results
A,      not A
      True,      False
     False,       True

else

Depending on the score entered, the output will be divided into cases that satisfy certain conditions and cases that do not, as shown below.

  1. If the score is 80 or more, output “Pass".
  2. Otherwise, output “Failure".

If you want to implement this kind of branching process, use else as follows.

Source
score = int(input('score: '))

if score >= 80:
    print('Pass’)
else:
    print('Failure’)

print('End’)
The result of entering 80
score: 80
Pass
End
The result of entering 79
score: 79
Failure
End

As shown above, if the specified condition “the value of the variable score is greater than or equal to 80" is True, the suite of lines following “if" will be executed. Otherwise (if the specified condition is False), the suite of lines following “else" will be executed.

The pass statement

Suppose there is a branching process that says, “If a certain condition is satisfied, do nothing.

For example, suppose we have the following process.

  1. If the score is 80 or higher, do nothing.
  2. Otherwise, output “Work harder".

In such a case, use the pass statement as follows

Source
score = int(input('score: '))

if score >= 80:
    pass
else:
    print('Work harder.’)

print('End’)
The result of entering 80
score: 80
End
The result of entering 79
score: 79
Work harder.
End

Depending on the programming language, a blank line may be sufficient. Python requires a pass statement; without a pass statement, Pycharm drew a red line at the beginning of else.

******************************************
0001
******************************************

When I run the file, I get the following error message.

Result when there is no pass statement
File “C:\Users\[user name]\PycharmProjects\pythonProject0001\0005\test0041.py", line 5
    else:
    ^
IndentationError: expected an indented block

elif

Suppose you have specified the processing for cases where condition 1 is satisfied and the processing for cases where condition 2 is satisfied, as shown below.

  1. If the score is 80 or more, output “A".
  2. If the score is 75 or higher, output “B".
  3. If the score is 50 or more, output “C".

In such a case, use elif as follows.

Source
score = int(input('score: '))

if score >= 80:
    print('A’)
elif score >= 75:
    print('B’)
elif score >= 50:
    print('C’)

print('End’)
The result of entering 80.
score: 80
A
End
The result of entering 70.
score: 75
B
End
The result of entering 50
score: 50
C
End

As shown above, you can add a conditional branch by using elif.

Now suppose there is an “other than" condition at the end, as shown below.

  1. If the score is 80 or higher, output “A".
  2. If the score is 75 or higher, output “B".
  3. If the score is 50 or higher, output “C".
  4. Otherwise, output “D".

In such a case, use else at the end, as shown below.

Source
score = int(input('score: '))

if score >= 80:
    print('A’)
elif score >= 75:
    print('B’)
elif score >= 50:
    print('C’)
else:
    print('D’)
The result of entering 49
score: 49
D
End

As shown above, elif can be used multiple times after if. If necessary, you can use else at the end.

nesting

Suppose you have a process that outputs “A" when the score is 80 or more, and “Good work." when the score is 90 or more, as shown below.

  1. If the score is 80 or more, output “A".
    1. If the score is 90 or higher, output “Good Work.".
  2. If the score is 75 or higher, output “B".
  3. If the score is 50 or higher, output “C".。
  4. Otherwise, output “D".

In the case of nested conditional branches as shown above, they can be implemented by using indentation as shown below.

Source
score = int(input('score: '))

if score >= 80:
    print('A’)
    if score >= 90:
        print('Good work.’)
elif score >= 75:
    print('B’)
elif score >= 50:
    print('C’)
else:
    print('D’)

print('End’)
The result of entering 90
score: 90
A
Good work.
End
The result of entering 89
score: 89
A
End

In the sample program above, the first if statement describes the second if statement in the suite. To write the corresponding suite for that second if statement, increase the indentation by one.

That’s all. I hope this is helpful to you.

Sponsored Links