Home > Net >  Function return None (TypeError: '>=' not supported between instances of 'NoneType
Function return None (TypeError: '>=' not supported between instances of 'NoneType

Time:09-07

I'm transforming a decimal number to bin subtracting:

class Table:

    def __init__(self) -> None:
        self.table = []

    def convert(self, decimal: int) -> list:
        self.table.append(1); decimal = decimal - 128 if decimal >= 128 or 0 else self.table.append(0)
        self.table.append(1); decimal = decimal - 64 if decimal >= 64 or 0 else self.table.append(0)
        self.table.append(1); decimal = decimal - 32 if decimal >= 32 or 0 else self.table.append(0)
        self.table.append(1); decimal = decimal - 16 if decimal >= 16 or 0 else self.table.append(0)
        self.table.append(1); decimal = decimal - 8 if decimal >= 8 or 0 else self.table.append(0)
        self.table.append(1); decimal = decimal - 4 if decimal >= 4 or 0 else self.table.append(0)
        self.table.append(1); decimal = decimal - 2 if decimal >= 2 or 0 else self.table.append(0)
        self.table.append(1); decimal = decimal - 1 if decimal >= 1 or 0 else self.table.append(0)

        return self.table
        
table = Table()

print(table.convert(128))

When I run the script i get this error:

Traceback (most recent call last):
  File "/home/raxabi/docs/Python/BinConverterClass/main.py", line 23, in <module>
    print(table.convert(128))
  File "/home/raxabi/docs/Python/BinConverterClass/main.py", line 9, in convert
    self.table.append(1); decimal = decimal - 32 if decimal >= 32 or 0 else self.table.append(0)
TypeError: '>=' not supported between instances of 'NoneType' and 'int'

How I can fix it?

CodePudding user response:

The reason is that the append method of a list returns None that gets appended to self.table in case decimal is greater than the other int.

The solution should be as simple as:

def convert(decimal: int) -> list:
    return [int(s) for s in '{0:b}'.format(decimal)]


print(convert(128))

Result:

[1, 0, 0, 0, 0, 0, 0, 0]
  • Related