Selection with the if statement
Learn how statements are selectively executed based on if conditions.
We'll cover the following...
The if
statement
Now we know that we have selection and iteration statements and that they work with conditions, so let’s see how we can write code that uses them. Let’s start with the most common selection statement, if
.
When using selection in our programs, we could argue that the application uses some sort of intelligence because it can now make decisions and do different things depending on various conditions. So, how can we make our applications smart? Well, the easiest way is with the use of if
statements, which are sometimes just referred to as conditions. In most languages, they’ll have a similar structure.
If we write a small program that asks the user for their age, the first part might look something like this:
print "Enter your age: "input age
Here, the program prints Enter your age:
on the screen. The user then enters an age and presses the Enter key to confirm the input. The value entered will be stored in the age
variable.
Now, we want to give different feedback depending on the age entered:
if age < 18 thenprint "You are young"end_if
Here, we have the condition where we check if the age is below 18
. If so, we’ll print the message, You are young
. The condition is that the age must be below 18
. If it’s 18
or above, nothing will happen, because the program will skip everything between them and end the if
...