The bin() Function


#1



https://www.codecademy.com/en/courses/python-intermediate-en-KE1UJ/0/4?curriculum_id=4f89dab3d788890003000096


Can you please explain why these two code segments are different? For the first block, Codecademy throws the error, "Oops, try again. It looks like you didn't print the binary representation of the number 2." The second completes the task, but they both produce the same output.


listx = [bin(x) for x in range(2,6)]
print "\n".join(listx)

#-------------------

for x in range(2,6):
    print bin(x)


#2

>>> listx = [bin(x) for x in range(2,6)]
>>> print "\n".join(listx)
0b10
0b11
0b100
0b101
>>>

>>> for x in range(2,6):
	    print bin(x)	
0b10
0b11
0b100
0b101
>>>

The first one is a list comp and the second is a plain old for-loop. Yeah, the output is same for both of them. They should work just fine for you, too :slight_smile:


#3

It's looking at the individual uses of print as opposed to the program's output, so it sees:

['0b10\n0b11\n0b100\n0b101']

vs

['0b10',
 '0b11',
 '0b100',
 '0b101']

#4

Ahh, thank you for clarifying.


#5

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