The first thing to try is to access a global KM variable instead of a local one. Local ones are available only inside the same shell that spawns the python code, and you didn't show us exactly where and how you spawned that python code.
The second thing is to show us how you spawned that python code. Did you run it from an action inside the same macro where the local variable was created? My guess is that this is your problem.
As I often say, there's a 10% chance that I'm wrong.
Thanks for your reply! I’ve attached a screenshot of my code.
I found this code online, so I wasn’t entirely sure about the best way to set up the variable.