CMIS 102 logical operators Logical operators are very important. 'and' is the logical AND operator. 'or' is logical OR. 'not' is logical NOT. The result of and-ing two values is True only if both values are True, it's False otherwise (i.e. if either or both are False). The result of or-ing two values is True if either or both of the values are True, it's False only if both values are False. These are straight out of classical logic, which is based on human thought and language. In real-life and human language: if sunny OR weekend then go outside #either sunny or weekend (or both) if sunny AND weekend then go outside #a sunny weekend if NOT rainy then go outside In logic and programming language: two truth values OR'ed together are True if either or both are True. Ex. booleanExpr1 or booleanExpr2 Is True if booleanExpr1 is True or if booleanExpr2 is True (or if both are True). Is False only if both are False. "Easy" to be True. two truth values AND'ed together are True only if both are True. Ex. booleanExpr1 and booleanExpr2 Is True if booleanExpr1 is True and booleanExpr2 is True. Is False if either or both are False. "Hard" to be True. a truth value NOT'ed reverses its truth value. Ex. NOT booleanExpr Is True if booleanExpr is False Is False if booleanExpr is True Truth tables: x not x - ----- F T T F x y x or y - - ------ F F F F T T T F T T T T x y x and y - - ------- F F F F T F T F F T T T Here's some natural examples used as conditions for if statements: notice the spacing style midExam = input("Input the midterm exam grade: ") if midExam=='A' or midExam=='B': print("congratulations!") elif midExam == 'C': print("could use some improvement") elif midExam == 'F': print("you're failing") score= eval(input("Enter the score: ")) if score<0 or score>100: print("Error. score must be between 0 and 100") if score>=90 and score<=100: #between 90 and 100, inclusive print("A") ans = input("Input your answer: ") if ans=='y' or ans=='Y': #allows user to enter either case y/Y print("thank you for the y or Y") if ans!='y' and ans!='Y': #anything but a y/Y print("whatever it is, it isn't a y or Y") month = eval(input("Enter month number: ")) if month==1 or month==3 or month==5 or month==7 or month==8 or month==10 or month==12: print("31 day month") elif month==4 or month==6 or month==9 or month==11: print("30 day month") else: print("February: 28 or 29 days") Operator precedence is important. In an expression like ab+2 or a (b+2)) or ((a b+2) or (a b+2 or a