Section 5.1 Intro: What we can do with Conditionals
So far, our programs have been a series of statements which always execute sequentially. But sometimes programs must change the statements they execute depending on the situation. For example, a messaging app might only set a message’s title bold if it has not been read by the user. Or a video game needs to update the position of all the characters that are not asleep. This is done with something called a selection or a conditional statement.
The following program changes the message that is printed, based on user input:
The program above accepts a body temperature from the user and checks to see if it indicates a fever. Lines 4-7 contain conditional statements. If the temperature is greater than 37.8 the print statement on line 5 executes, otherwise the print statement on line 7 exectutes. Conditional statements like this create a branching effect in our program: the program no longer runs strictly sequentially.
This chapter will further detail how to use conditional statements.
Subsection 5.1.1 Learning Goals
- To understand boolean expressions and logical operators
- To understand conditional execution
- To be able to write a boolean function
- To know when to use binary, unary, chained and nested conditional statements
Subsection 5.1.2 Objectives
- To properly evaluate a (compound) boolean expression
- To use parenthesis to properly demonstrate operator precedence
- To use conditional statements to properly branch code
You have attempted of activities on this page.