Why The Bracket Can't Be Omitted In Int.to_bytes?
Solution 1:
Without the brackets, Python is attempting to parse 3.to_bytes as a floating point number; that is, it's trying to make 3.<something> and there's a syntax failure when you try to access to_bytes without the dot.
If you add an extra dot, it finishes the parsing of the float and attempts to access the method, which doesn't exist:
>>>3..to_bytes(2, "big")
Traceback (most recent calllast):
File "<stdin>", line 1, in<module>
AttributeError: 'float' object has no attribute 'to_bytes'If you have it in the brackets it passes because it doesn't try to make the floating point number. You can also run it with a space to get around this:
>>> 3 .to_bytes(2, "big")
b'\x00\x03'>>> 3.to_bytes(2, "big")
File "<stdin>", line 13.to_bytes(2, "big")
^
SyntaxError: invalid syntax
When you store the int in a variable, Python doesn't attempt to parse it as a float, which is why you don't see it that way as well when using x.to_bytes().
Solution 2:
Because 3. by itself is a decimal (float type) number. So 3.to_bytes is parsed as (3.)to_bytes which is invalid. So you need to say (3).to_bytes to give the dot the meaning you intended.
Post a Comment for "Why The Bracket Can't Be Omitted In Int.to_bytes?"