Line: | Conditional Line | Type: | Walkthrough |
You should have completed: | Getting Numbers | This topic leads to: | Magic Numbers Counting Up Again |
In order to tackle most problems, it is necessary to sometimes do one thing, and sometimes do another (or nothing). This is selection. In this example, the user is asked for their age, and based on that age we select whether to tell them that they are legally old enough to take the driving test, or to tell them how many years they must wait.
Note that if the condition in the if statement does not evaluate to true, the next statement after the if, the message command, is ignored and execution proceeds to the next statement.
The program reports the user is unable to take the test at age 17. Why is this? We need to be very precise in our instructions within programs, 17 is not greater than 17, it is equal to it, therefore the condition is false.
This applies automatic formatting to your code, in particular applying tabbed indentation. You will see that the if and else statements now line up vertically, and the statements controlled by that selection are indented relative to them. This vertical alignment makes code a lot easier to read and understand and is very good programming practice.