1. Python supports the following logical operators:
and
→ if both operands are true, the condition is true, e.g.,(True and True)
isTrue
,or
→ if any of the operands are true, the condition is true, e.g.,(True or False)
isTrue
,not
→ returns false if the result is true, and returns true if the result is false, e.g.,not True
isFalse
.
2. You can use bitwise operators to manipulate single bits of data. The following sample data:
x = 15
, which is0000 1111
in binary,y = 16
, which is0001 0000
in binary.
will be used to illustrate the meaning of bitwise operators in Python. Analyze the examples below:
&
does a bitwise and, e.g.,x & y = 0
, which is0000 0000
in binary,|
does a bitwise or, e.g.,x | y = 31
, which is0001 1111
in binary,˜
does a bitwise not, e.g.,˜ x = 240
*, which is1111 0000
in binary,^
does a bitwise xor, e.g.,x ^ y = 31
, which is0001 1111
in binary,>>
does a bitwise right shift, e.g.,y >> 1 = 8
, which is0000 1000
in binary,<<
does a bitwise left shift, e.g.,y << 3 =
, which is1000 0000
in binary,
* -16
(decimal from signed 2’s complement) — read more about the Two’s complement operation.
Exercise 1
What is the output of the following snippet?
1 2 3 4 5 |
x = 1 y = 0 z = ((x == y) and (x == y)) or not(x == y) print(not(z)) |
False
Exercise 2
What is the output of the following snippet?
1 2 3 4 5 6 7 8 9 10 11 |
x = 4 y = 1 a = x & y b = x | y c = ~x # tricky! d = x ^ 5 e = x >> 2 f = x << 2 print(a, b, c, d, e, f) |
0 5 -5 1 1 16
Ex. 3
What is the output of the following code snippet?
1 2 3 4 |
print((3, 1) in {1: 'a', 'b': 2, (3, 1): 10}, end = " ") print(3 not in {1: 'a', 'b': 2, (3, 1): 10}, end = " ") print('a' in {1: 'a', 'b': 2, (3, 1): 10}, end = " ") print('a' in {1: 'a', 'b': 2, (3, 1): 10}.values(), end = " ") |
Ex. 4
What is the output of the following code snippet?
1 2 3 4 5 6 |
a = 3 b = 6 x = 2 * a >= b == (b % a != 0) print(x) |