13.4. And, Or, and Not¶
13.4.1. And¶
and
is what we use when we want to verify that two things are BOTH true.
A common use of and
is to check that a value is in a range between a minimum value and a maximum
value. For example, to determine if a grade is a “B”, we need to make sure it is at least 80 but
is also less than 90. We can use and
to combine grade >= 80
and grade < 90
so that
both must be true for the overall condition to be true. Try changing grade to different values
as you run this program:
- 1 to 10
- This would be true if the second expression was x <= 10.
- 0 to 9
- This would be true if the first logical expression was x >= 0.
- 1 to 9
- The "condition true" will only be printed when x is greater than 0 and less than 10 so this is the range from 1 to 9.
Given the code below, what describes the values of x that will cause the code to print “condition true”?
if x > 0 and x < 10:
print ("condition true")
print ("All done")
13.4.2. Or¶
or
is a way to give multiple ways to satisfy some criteria.
For example, maybe our program is going to ask the user if they have a bag to check.
We want them to be able to answer either “yes” or just “y”. If you input either answer when
asked for an input by this program, it will tell you there will be an extra fee.
- 0 to 10
- If x was 5, but ``x < 0`` and ``x >= 10`` are false.
- 1 to 10
- If x was 5, but ``x < 0`` and ``x >= 10`` are false.
- negative values
- That is partially correct. But what values would be true because they made ``x >= 10`` true?
- negative values or 2+ digits
- Correct
Given the code below, what describes the values of x that will cause the code to print “condition true”?
if x < 0 or x >= 10:
print ("condition true")
print ("All done")
13.4.3. Not¶
Finally, not
is primarily used with functions that return a Boolean value. For instance,
isalnum
is a string function that checks to see if all of the characters are alphanumeric
(letters or digits). This program wants to know the opposite of that - if there is at least
one special symbol, it wants to make the use pick a new username. So not
is used to reverse the result of isalnum
. If the user gives input that includes a symbol,
isalnum
will return False
, but the not
will turn that into True
which means
that we will execute the line of code that asks them to try again.
Notice that the program currently only will ask you to try again once. If we want it to keep
asking the user to try again until they get it right, we would need a loop. Try changing the
if
into a while
- the program will keep asking you to try again until you get it right.