Home > OS >  Python: Variable initialized in if statement not defined outside that block
Python: Variable initialized in if statement not defined outside that block

Time:01-22

I have the problem in Python 3.9 that a variable defined in an if block is reported "undefined" when used outside that block.

When I initialize the variable before the if block and change it's value inside the block, it keeps the value as defined before the block.

In both cases the condition of the if statement evaluates to true.

I looked for other posts but I only find that the changes made inside the if should also be visible outside the scope of the if.

How can I "export" the value to outside the if?

CodePudding user response:

Python conditionals don't have that type of scope. For example, if we have

if True:
    a = 1
print(a)

then this will print 1. Similarly with mutation,

b = 1
if True:
    b = 2
print(b)

prints 2. Are you sure the conditional evaluates to True?

CodePudding user response:

Can you post your code or a simplified snippet that showcases it? As you said in your question, Python variable scope should simply be based on the block it was created in, so it makes sense that it's undefined after trying to use it outside of the if, but it is interesting that it doesn't change value after the if.

As BrownieInMotion said, you can always change the if statement to be a function and "export" the variable by returning it, but there is more likely some other issue going on, like the condition not evaluating the way you intended or perhaps a duplicate variable name.

CodePudding user response:

The problem is probably that the if condition is not true in some cases. I'll have to redesign my algorithm.

  • Related