DEV Community

Saravanan Cn
Saravanan Cn

Posted on

My Python Learning Journey: Bitwise, Shift and Ternary Operators 🐍

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)
Enter fullscreen mode Exit fullscreen mode

Output:

1
Enter fullscreen mode Exit fullscreen mode

2. Bitwise OR (|)

The bitwise OR operator returns 1 when at least one corresponding bit is 1.

print(5 | 3)
Enter fullscreen mode Exit fullscreen mode

Output:

7
Enter fullscreen mode Exit fullscreen mode

3. Bitwise XOR (^)

XOR stands for Exclusive OR. It returns 1 when corresponding bits are different.

print(5 ^ 5)
print(5 ^ 3)
Enter fullscreen mode Exit fullscreen mode

Output:

0
6
Enter fullscreen mode Exit fullscreen mode

4. Bitwise NOT (~)

The bitwise NOT operator reverses the bits. In Python, it follows this formula:

~n = -(n + 1)

Example:

print(~7)
print(~0)
Enter fullscreen mode Exit fullscreen mode

Output:

-8
-1
Enter fullscreen mode Exit fullscreen mode

5. Left Shift (<<)

The left shift operator moves binary bits to the left.

print(5 << 1)
Enter fullscreen mode Exit fullscreen mode

Output:

10
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

2
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

Pass
Enter fullscreen mode Exit fullscreen mode

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)