6. Slide to the Left! ... I understand the bit operators but not the code


#1

I think I understand what the bit operators do, but I'm not following what the code does or what we're supposed to learn from this exercise. I'm pretty new to coding in general; this is my understanding of what we're doing:

First we set a variable shift_right equal to 12 in binary (0b1100), and another variable shift_left equal to 1 in binary (0b1).

We're then supposed to use the bit operators to chop off the two right-most zeroes of the binary number stored in the first variable, and add two zeroes to the right of binary number in the second variable. Changing them from 12 to 3 and 1 to 4 in binary respectively.

Lastly, we print bin() on each of our variables to see the resulting binary numbers.

When I first tried this I simply put:

shift_right = 0b1100
shift_left = 0b1

# Your code here!
shift_right >> 2
shift_left << 2

print bin(shift_right)
print bin(shift_left)

But I got an error message: Oops, try again. Did you set shift_right = shift_right >> 2 ?

So I changed it to below, and it works.

shift_right = 0b1100
shift_left = 0b1

# Your code here!
shift_right = shift_right >> 2
shift_left = shift_left << 2

print bin(shift_right)
print bin(shift_left)

Why doesn't my first attempt work? With the way CodeCademy apparently wants it, aren't we just re-writing the first variables? Do the operators not take variables directly or something, while a variable with the operator on a variable will work? It just seems inconsistent to me... but I'm kind of tired so maybe I'm just missing something obvious.


#2

No different from:

a = 5
a + 5  # no effect

#3

The first attempt does not actually change the state, that's why it must be assigned back onto itself (as in the second example).


#4

OH! Ok. Thanks to both ionatan and mtf for your quick replies. I understand now.

If I had put print in front of my first attempts, I would have at least seen that the code DID do something (though codecademy still probably wouldn't accepted it). But since I didn't return or store that somehow, it just got lost in the ether.


#5
a >> 2

b + 5

The above are known as expressions. They represent a value which must be yielded to a variable, as we've seen. We can complete the state change in one step by using an in place assignment...

a = 0b1100
a >>= 2
print (a, bin(a))    # 3 0b11
b = 37
b += 5
print (b)            # 42

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.