Python Day 4: Bitwise Operators and Ternary Operator
Bitwise XOR (^) XOR stands for Exclusive OR. The result is 1 when both bits are different. If both bits are the same, the result is 0. a b a ^ b True True False True False True False True True False False False Example: print ( 4 ^ 5 ) # 1 Binary calculation: 4 = 100 5 = 101 XOR = 001 = 1 Binary 001 means: (0 * 4) + (0 * 2) + (1 * 1) = 1 Another example: no1 , no2 = 5 , 5 print ( no1 ^ no2 ) # 0…
Day 4 of Python focused on bitwise operators and the ternary operator. XOR (^) stands for Exclusive OR. The result is 1 when both bits differ, and 0 when they are the same. For example, 4 (100 in binary) XOR 5 (101 in binary) equals 1 (001 in binary).
The Bitwise NOT operator (~) reverses the bits of a number. In Python, the result can be calculated using the formula ~n = -(n + 1). For instance, ~4 equals -5, and ~0 equals -1.
Shift operators move bits left or right. The left shift (<<) multiplies positive integers by 2 for each shift to the left. For example, 4 left-shifted by 1 becomes 8. The right shift (>>) divides positive integers by 2 for each shift to the right, rounding down. Thus, 4 right-shifted by 1 equals 2.
The ternary operator, also known as the conditional expression, enables writing simple if-else conditions in a single line. Its syntax is value_if_true if condition else value_if_false. For example, given no1 = 10 and no2 = 20, the expression result = 100 if no1 > no2 else 200 will assign 200 to result, as no1 is not greater than no2.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.