Another little phyton question

Hey there. I’ve been going with my phyton journey, and i tried to make a simple script.
The objective is to make a ball move back and forth (if that’s how it’s spelled). But i’m getting an error on the console, in the lines 29 and 23:

KeyError: 'value = gameOb[key]: KX_GameObject, key "dx" does not exist'

And here’s the code:

import bge



def main():


    cont = bge.logic.getCurrentController()
    own = cont.owner
    limit = 4
    
#Now the movement.
    def Init():
    
        if not 'init' in own:
            own['init'] = 1
            
            own['dx'] = 0.1
    
    def Update():
        own.position.x += own['dx']
        if (own.position.x < -4 or own.position.x > 4):
            own['dx'] *= -0.1
    
    own.position.x += own['dx']
    
    Init()
    Update()
    
    
main()



In line 25 you try to use the ‘dx’ property before you’ve ever called Init(). Make sure you move that after your first call to Init().

As a side note, things are a lot easier to look at and debug when they’re organized. You’ve declared two sub-methods right in the middle of your main method, splitting main’s code in half. This makes it hard to tell what code belongs to what method and is just ugly in general. Practicing good code organization now will save you a lot of head aches in the future.

Thanks! I actually added the second sub-method by error, anyway, fixed the whole script :slight_smile: