>> 3.to_bytes(2,"big") File "", line 1 3....">

Why can't the bracket be omitted in int.to_bytes?

>>> x=3
>>> x.to_bytes(2,"big")
b'\x00\x03'
>>> 3.to_bytes(2,"big")
  File "<stdin>", line 1
    3.to_bytes(2,"big")
             ^
SyntaxError: invalid syntax
>>> (3).to_bytes(2,"big")
b'\x00\x03'

Why can't I omit the bracket 3.to_bytes(2,"big")? Is there a function in this bracket?

+1
source share
2 answers

Without parentheses, Python tries to parse 3.to_bytesas a floating point number; those. trying to make 3.<something>there syntax failure when trying to access to_byteswithout a point.

If you add an extra point, it will complete the parsing of the float and try to access a method that does not exist:

>>> 3..to_bytes(2, "big")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'to_bytes'

If you have this in parentheses, it passes because it is not trying to make a floating point number. You can also run it with space to get around this:

>>> 3 .to_bytes(2, "big")
b'\x00\x03'
>>> 3.to_bytes(2, "big")
  File "<stdin>", line 1
    3.to_bytes(2, "big")
             ^
SyntaxError: invalid syntax

int , Python float, x.to_bytes().

+1

3. ( ) . , 3.to_bytes (3.)to_bytes, . (3).to_bytes, , .

+1

Source: https://habr.com/ru/post/1535903/


All Articles