If…Then…Else
In the previous section we looked at the If…Then statement that is used for making a decision. When using the If…Then statement a section of code is performed only if the Boolean statement is true. If the Boolean statement is false, nothing happens. In some situations, if the Boolean statement is false and the section of code is not performed, you would like an alternative piece of code to be performed instead. In this case an optional Else statement can be used. The If…Then…Else statement (in most computer programming languages), takes the generic form of:
In the previous example of asking the user how many students were in the class, you might have noticed that the user was given no feedback if there were 30 or fewer students. This can add confusion for the user; they might be unsure if the program worked correctly.
An example of what this would look like using an If .. Then .. Else statement is shown below:
Top-Down Design for If…Then…Else statement
Flowchart for If…Then…Else statement
Pseudocode for If…Then…Else statement
Code for If…Then…Else statement
constants.py
.. literalinclude:: ../../code_examples/3-Structured_Problem_Solving/7-If_Then_Else/Python/constants.py
:language: python
:linenos:
:emphasize-lines: 8-9
main.py
.. literalinclude:: ../../code_examples/3-Structured_Problem_Solving/7-If_Then_Else/Python/main.py
:language: python
:linenos:
:emphasize-lines: 19-22