<< Hide Menu
2 min read•june 18, 2024
Minna Chow
Milo Chang
Minna Chow
Milo Chang
Earlier, we introduced the concept of sequencing, selection and iteration. The selection process primarily takes the form of conditional statements known as if statements.
Selection statements in programming are used to control the flow of execution in a program. They allow you to specify requirements, or conditions, that must be met in order for certain parts of the program to be executed.
If statements execute different segments of code based on the result of a Boolean expression. Here's the format of a basic if statement in Pseudocode...
strawberries_in_fridge = 7
if strawberries_in_fridge >= 7:
print("You can make strawberry shortcake!")
The code in the if statement is executed only if the condition is met. In this case, the condition is the boolean expression strawberries_in_fridge ≥ 7. The condition is true, so the code inside the if statement (the print statement) will execute.
If strawberries_in_fridge was less than seven in this case, the program would just skip over the code inside the statement and continue to the next part of the program.
However, if statements can also have else statements attached to them that specify what would happen if the condition wasn't met. Here they are in Pseudocode...
strawberries_in_fridge = 7
if strawberries_in_fridge >= 10:
print("You can make strawberry shortcake!")
else:
print("Sorry, no shortcake for you!")
Else statements will only run when the condition attached to an if statement comes back false. In this case, because the if statement isn't true, the program will run the else statement instead.
© 2024 Fiveable Inc. All rights reserved.