I'm continuing my Python learning journey. Today, I learned about bitwise operators, shift operators, and the ternary (conditional) operator.
1. Bitwise AND (&)
The bitwise AND operator returns 1 when both corresponding bits are 1.
print(5 & 3)
Output:
1
2. Bitwise OR (|)
The bitwise OR operator returns 1 when at least one corresponding bit is 1.
print(5 | 3)
Output:
7
3. Bitwise XOR (^)
XOR stands for Exclusive OR. It returns 1 when corresponding bits are different.
print(5 ^ 5)
print(5 ^ 3)
Output:
0
6
4. Bitwise NOT (~)
The bitwise NOT operator reverses the bits. In Python, it follows this formula:
~n = -(n + 1)
Example:
print(~7)
print(~0)
Output:
-8
-1
5. Left Shift (<<)
The left shift operator moves binary bits to the left.
print(5 << 1)
Output:
10
For non-negative integers, shifting left by one position is equivalent to multiplying by 2.
6. Right Shift (>>)
The right shift operator moves binary bits to the right.
print(5 >> 1)
Output:
2
For non-negative integers, shifting right by one position is equivalent to floor division by 2.
7. Ternary Operator (Conditional Expression)
A ternary expression selects a value based on a condition.
marks = 75
result = "Pass" if marks >= 40 else "Fail"
print(result)
Output:
Pass
If the condition is true, Python selects "Pass"; otherwise, it selects "Fail".
What I Learned Today
- Bitwise AND, OR, XOR, and NOT
- Two's complement basics
- Left and right shift operators
- Ternary conditional expressions
- Binary operations and their decimal results
I'm practising these concepts with small Python programs and strengthening my programming fundamentals step by step.
Every day is an opportunity to learn something new! 🚀
Top comments (0)