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:

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.

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.

You have attempted of activities on this page