Using and in Boolean if Statements
In this lesson and the next, you’ll see some typical Boolean contexts where an
and operator might be used. Boolean contexts typically appear as the conditions in
00:15 These instructions modify the flow of execution in your program, either selecting one section of code or another to be executed or selecting a section of code to be repeated.
You can create more effective conditions to direct the flow of your program through the use of expressions which use the
Let’s first see an example using the
if statement. Here is a simple segment of code that describes a person based on his or her age, following an input statement, which will allow us to test it.
To be classified as an adult in this example means to be older than eighteen and up to and including sixty-five. So you need to combine two inequalities,
age is greater than
age is less than or equal to
65, with the operation
and to indicate that an age must meet both conditions to be considered an adult.
And you can see other classifications use
and to connect inequalities that give lower and upper limits on
age to be in that category.
01:23 So in the terminal, you can run this a few times to see each branch being selected.
15 is greater than or equal to
0, but it’s not less than or equal to
9. So the first condition is false. So the program drops to the next condition.
15 is greater than
15 is also less than or equal to
18. Since both these conditions are true, the
and of them is
True, and the program executes the then code for this conditional, telling us you’re an adolescent.
If you try a younger age, here, both of the expressions in the first condition are true:
age is greater than or equal to
0 and less than or equal to
02:16 So the entire condition is true, so the child phrase should be output. If you continue this, you can find ages that fit the other two conditions as well.
30 is greater than
18 and less than or equal to
65, putting us in the adult category.
70 makes at least one expression fail in each of the first three conditions. It’s not less than or equal to
9, not less than or equal to
18, not less than or equal to
So it’s not until the last expression,
> 65, that we get a true condition.
In the next lesson, you’ll see expressions using
Become a Member to join the conversation.