Python Forum

Full Version: Variable definitions inside loop / could be better?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear Python Community,

I use Python a lot for my company projects, and I ussually do some taslks that seems to
repeats every time. For instance,I use to define vars prior to a loop, so I can use them
a few lines later in the code,
something like:

result = None
if cond_x == 'x':
    result = ....
print(result)
I feel there could be a better way to handle this. Of course, I am thinking something different
from the global tag, because it is just need in the current variable space.

Can you share your thoughts on this?

Best regars,

Gustavo A. Garcia
Gibgo
The example code does not have a loop so it does not show the problem you are having doubts about.
global is not applicable here.

I think your pattern is fine. Sometimes I do this when I need to initialize a variable to one of two values based on a condition.
a = b if condition else c
If you want to know how to make sure a variable is assigned when you assign in a loop, provide an example that uses a loop.