Professional Documents
Culture Documents
Multiway Conditional Check, Nested If, Bitwise Ops and Membership Operator
Multiway Conditional Check, Nested If, Bitwise Ops and Membership Operator
Multiway Conditional Check, Nested If, Bitwise Ops and Membership Operator
Membership Operator
August 9, 2022
100
100
No Profit No Loss
[10]: # When you have to say whether the given number is +ve or -ve
n = int(input())
if n > 0:
print('+ve')
elif n < 0:
print('-ve')
else:
print('Zero')
-12
-ve
1
20 30 10 –> B is the largest
30 10 20 –> A is the largest
30 20 10
a is largest: 30
-15
Invalid
2
2 Nested if statements
• Writing if statements inside other if statements is called nested if statements
2.1 Finding out the largest of three distinct integers using nested if statements
(This time using nested if)
[26]: a, b, c = map(int, input().split()) # 20 10 30
if a > b: # 20 > 10
if a > c: # 20 > 30
print(f'a is largest: {a}')
else:
print(f'c is largest: {c}')
else:
if b > c: # 20 > 30
print(f'b is largest: {b}')
else:
print(f'c is largest: {c}')
10 30 20
b is largest: 30
3 Bitwise Operators
• Operates on bit level.
• Need to have the knowledge on binary number system.
• & –> Bitwise AND
• –> Bitwise OR
• ^ –> Bitwise XOR
• « –> Bitwise left shift
• » –> Bitwise right shift
[27]: 8
[28]: # Bitwise OR
11 | 12
[28]: 15
3
[29]: 7
4
Decimal: 75
Binary: 1001011
75 –> 1
37 –> 1
18 –> 0
9 –> 1
4 –> 0
2 –> 0
1 –> 1
Bottom up (1001011)
• Write the powers of 2 (starting from 20 ) from right to left under each bit
1 0 1 1 1
16 8 4 2 1
And add all the numbers under 1 to get the decimal representation
16 + 4 + 2 + 1 = 23
Some more examples
Example 2:
Binary: 1101101
Decimal: 109
Seperating bits
1 1 0 1 1 0 1
64 32 16 8 4 2 1
Adding all the numbers that are under 1 to get the decimal representation
64 + 32 + 8 + 4 + 1 = 109
Example 3:
5
Binary: 1111011
Decimal:
Seperating bits
1 1 1 1 0 1 1
64 32 16 8 4 2 1
Adding all the numbers that are under 1 to get the decimal representation
64 + 32 + 16 + 8 + 2 + 1 = 123
[ ]: ### Bitwise OR
print(11 | 12)
# 1011
# 1100
# ----
# 1111 --> 15
6
# 1011
# 1100
# ----
# 0111 --> 7
[37]: # 5 & 11
print(5 & 11)
# 0101
# 1011
# ----
# 0001 --> 1
# 1 0 1 1 0
# 16 8 4 2 1 --> 22
22
112
7
[41]: print(14 >> 3)
# 14 // 8
4 Membership Operators
• Check if the given value is a member of community
• MLA –> Member of something
• MP –> Member of
• in
• not in
• It checks if an element is a member of an iterable - string, list, set, range, tuple
True
False
True
False
True
False
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [48], in <cell line: 1>()
----> 1 print(1 in 100)
True
8
[50]: print('h' not in 'hello')
False
True
True
False
Enter a character: z
Consonant
Enter a character: z
Consonant
Enter a character: Z
Consonant
9
else:
print('False')
1456
False
Enter a character: _
Special character
10