Alright, so now that we are familiar with the concepts of True and False, let’s look at three new operators (called logical operators) – AND, NOT and OR.
- The ‘not’ operator takes one operand (one Boolean variable or statement etc. ) and just inverts it.
Type and run
print(not True)
print(not(7>8)==True)
In the first print – we start with True, then invert it to get False.
In the second print – Start with 7>8 which is False. Invert this False to get True. Then do True==True – which is True!
2. The ‘and’ operator takes two operands. It returns a ‘True’ only if the operands on both side of it are ‘True’ . If at least one of them evaluates as ‘False’ – the end result is ‘False’.
Type and run
Ibrahim_cgpa=2.8
Ibrahim_semester =9
Rokeya_cgpa=3.3
Rokeya_semester =4
#A student can do an internship at Company X only when
#his or her CGPA is greater than 2.5
#AND
#he or she has completed at least 2 years (6 semesters)
print(“Ibrahim can apply for the internship: %s” %(Ibrahim_cgpa>2.5 and Ibrahim_semester>=6) )
print(“Rokeya can apply for the internship: %s” %(Rokeya_cgpa>2.5 and Rokeya_semester>=6) )
3. The ‘or’ operator also works with two operands. It is the more relaxed guy, compared to ‘and’ 😀 It yields ‘True’ as long as one of the operands is ‘True’. Both operands do not need to be true!
# Company X decides to relax semester completion requirments if student has leadership experience
Rokeya_IEEEevents = 3
print(“Rokeya can apply for the internship: %s” %(Rokeya_semester>=6 or Rokeya_IEEEevents>0) )
Exercise:
Let us do some True and False exercise like the way we used to do in school!
Look at the following print commands and deduce where each of the statement inside the print command is True or False. Do this mentally and do not print the statements yet.
- print(42>40)
- print(7*3>20)
- print(21<=7*3)
a=[]
b=[]
c=a
d = [‘bag has something’]
- print( a is b)
- print(a is b or a is c)
- print(not a)
- print(not d)
- print(a==c and a != b)
- print(8.0 != 8)
- print(9.0 is 9)
- print(‘feluda’ is not ‘shonku’)
- print(2+3-4*6 <= 0)
Then write your answer in Markdown mode. Translate each statement to ‘English’ and then write on the right whether it is true or false. For example, translating and writing the first one in Markdown is simply this:
42 is greater than 40: True
Then in Code mode, run the code ( print all the sentences given) and double check with your Markdown answers.