3.1.3.6 SECTION SUMMARY
Key takeaways
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 TrueisFalse.
2. You can use bitwise operators to manipulate single bits of data. The following sample data:
x = 15, which is0000 1111in binary,y = 16, which is0001 0000in 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 0000in binary,|does a bitwise or, e.g.,x | y = 31, which is0001 1111in binary,˜does a bitwise not, e.g.,˜ x = 240, which is1111 0000in binary,^does a bitwise xor, e.g.,x ^ y = 31, which is0001 1111in binary,>>does a bitwise right shift, e.g.,y >> 1 = 8, which is0000 1000in binary,<<does a bitwise left shift, e.g.,y << 3 =, which is1000 0000in binary,
Exercise 1
What is the output of the following snippet?
x = 1
y = 0
z = ((x == y) and (x == y)) or not(x == y)
print(not(z))
Exercise 2
What is the output of the following snippet?
x = 4
y = 1
a = x & y
b = x | y
c = ~x
d = x ^ 5
e = x >> 2
f = x << 2
print(a, b, c, d, e, f)
Comments
Post a Comment