Search code examples
pythonmicropythonbbc-microbit

Can someone explain what is happening with this piece of micro python


Just started playing with a BBC micro:bit. One of the examples has this line of code

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

It generates set of images. In trying to figure out what is going on I wrote this piece of code

class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)


flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )

which produces

python3 test.py 
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

Thanks


Solution

  • In invert() You need to pass some int values and return any int value. In your code you are not returning any int or float value in your invert() function. Try this

    class Image:
        def __init__(self,*args):
            print ("init")
            for a in args:
                print (a)
    
        def invert(self, *args):
            print ("invert")
            for a in args:
                return a
    flash = [Image().invert(1,)*(i/9) for i in range(9, -1, -1)]
    print (flash)
    

    This will work