- "text": "Logical operators\nSuppose we wanted to test if two things were True at the same time, or to see if at least one of two things were True. This is where logical operators are useful.\nThe and operator allows us to check if two conditions are both True, while the or operator allows us to check if at least one of two conditions is True. For example:\n\nand operator\nLet’s use the example from earlier where we checked if x was greater than 10 and less than 20. We can use the and operator to check both conditions at the same time:\n\n# x = 15\n# Test if x is greater than 10 and x is less than 20\nx > 10 and x < 20\n\nTrue\n\n\n\n\nor operator\nIf we wanted to check if x was either less than 5 or greater than 10, we could use the or operator:\n\n# x = 15\n# Test if x is less than 5 or x is greater than 10\nx < 5 or x > 10\n\nTrue\n\n\n\n\nnot operator\nThe not operator allows us to check if a condition is False and returns a True, or vis versa. For example, one way we could check if x is not greater than 10 would be to write:\n\n# Test if x is NOT greater than 10\n# x = 15\nnot x > 10\n\nFalse\n\n\n\n\nCombining logical operators\nWe can also combine logical operators using parentheses to check multiple conditions at the same time. When we do this we need to be careful how we group those and and or statements together. Given these two statements when x is 15, the first example will return True:\n\n# Set x to 15\nx = 15\n\n# Test if x is equal to 15 or if x is less than 20 and greater than 18\nx == 15 or (x < 20 and x > 18)\n\nTrue\n\n\nWhile the second example will return False:\n\n# Test if x is equal to 15 or less than 20 and if x is greater than 18\n(x == 15 or x < 20) and x > 18\n\nFalse\n\n\n\n\n\n\n\n\nExercise 3\n\n\n\n\nCreate an if statement to evaluate whether x is between 5 and 10, inclusive of both 5 and 10. If so, have Python print out “x is between 5 and 10”.\nExtend this same conditional to if x is not between 5 and 10, inclusively, but is above 10, then Python it print out “x is greater than 10”.\nExtend this same conditional to if x is not between 5 and 10, inclusively, and also not above 10, then have Python return “x is less than 5”.\n\n\n\n\nNext Lesson >>\nBack to Schedule",
0 commit comments