Vision is programming is events based. Components (and components inside of templates, as well as templates themselves once you instantiate them) have a bunch of different event listeners/extension functions. You need to choose which event triggers your script. Do you want it when some property on the component changes? When the mouse is clicked, or when the mouse is released? When something is double clicked? Etc.
Do what was suggested, put this code inside a function, and then decide where the appropriate time to call that function is, which extension function? A simple example for running the function every time a new selection is made on the dropdown would be to put this under the property change script of the component -
from myModule import myFunction
if event.propertyName == 'selectedValue':
event.source would pass a reference to the dropdown to your function so you could look at the dropdown data and manipulate background color.
Just a side note though, the expression language is pretty powerful, and it looks like your just basing your background color on two named queries. Why not add two custom properties on your dropdown, one for each query result, and then using those values, bind your background color property on an expression that uses those values?