Bottle Bank
Reading Questions
Quiz
Logical Operators
- Numerical operators have numeric values for operands
- Logical operators (or Booean operators) have boolean values for operands - print(True and False) print(False or True) print(not False)
- These are useful in conditional statements when you have complex conditions
- For example, if you want to check if a number is in a range - x = int(input('enter an integer: ')) if x >= 0: if x <= 100: print('you entered a number in the range [0, 100]') else: print('you did not enter an number in the range [0, 100]') else: print('you did not enter an number in the range [0, 100]')
- This can be simplified with a logical operator - x = int(input('enter an integer: ')) if x >= 0 and x <= 100: print('you entered a number in the range [0, 100]') else: print('you did not enter a number in the range [0, 100]')
- Note, the operands must be Booleans!
- The following will not work - print(x == 1 or 2 or 3) print(x > 0 and < 10)
- Also note, and, or and not, do not have the same precedence - x = 2 print(not x == 1 or x == 2)
- Is not equivalent to - x = 2 print(not (x == 1 or x == 2))
Boolean Functions
- Can have variables equal to boolean values - x = int(input('enter an integer: ')) if x >= 0 and x <= 100: x_is_in_range = True else: x_is_in_range = False if x_is_in_range == True: print('you entered a number in the range [0, 100]') else: print('you did not enter a number in the range [0, 100]')
- Setting a variable to a Boolean value can usually be simplified by using an expression - x = int(input('enter an integer: ')) x_is_in_range = x >= 0 and x <= 100 if x_is_in_range == True: print('you entered a number in the range [0, 100]') else: print('you did not enter a number in the range [0, 100]')
- This can make the code more readable
- Note that if x_is_in_range == True:is a little redundant
- It can be simplified to - if x_is_in_range:which also reads a little better- x = int(input('enter an integer: ')) x_is_in_range = x >= 0 and x <= 100 if x_is_in_range: print('you entered a number in the range [0, 100]') else: print('you did not enter a number in the range [0, 100]')
- Can also do this with a function that returns a Boolean value - def is_in_range(x): return x >= 0 and x <= 100 x = int(input('enter an integer: ')) if is_in_range(x) print('you entered a number in the range [0, 100]') else: print('you did not enter a number in the range [0, 100]')