I do have a question i have a python code that has some variables declarations and sensors identifying. also it has a function inside called RUN my problem is that when i use an always sensor with a python controller, it only reads RUN function and it ignores the variables i declared before. even though it doesn't ignore the identified serialport. how can i make the sensor reads the whole code once and loop the run function?
Python controllers in Script mode execute the code starting with the first line of the script.
Python controllers in Module mode behave differently. At the first call the module initializes by running the module level code starting with the first line of the module. Be aware this runs once only!.
The code the Python controller is supposed to run is placed inside a function definition (def). This code gets executed at each trigger of the controller. The execution starts with the first line of the called function and ends when leaving the function (on return or latest at the end of the function definition).
You can declare module variables within module level code (code outside of the functions). This variables will persist as long as the module exist. Be aware things like current scene, current controller, or controller's owner should not be stored in a module variable. This can easily lead to confusing and hard to investigate behavior. Better read these data from context (bge.logic) inside the called function.
Example: imaging you have two objects that both call the module. When you store the reference to the current controller at module level, the variable will refer to the controller which executed the code first (e.g. controllerA). This will be plain incorrect when running the code from the other controller (controllerB) as the variable refers to controllerA.