By Johan Mocke via Discussions on Python.org at 11Jul2022 22:34:
for key in question_access:
if (key[ādeviceā][āprofileā][āidā]) == 155975:
print(ātrueā)
elif (key[ādeviceā][āprofileā][āidā]) != 155975:
s = (key[ādeviceā][āidā])
print(s)
This works perfectly fine,
Can you clarify what āperfectly fineā means? āRuns without errorā does
mean everything you might hope. āprints the string in sā might mean
more.
however, if I try to use the same variable (s) further down in my code,
it says (s) is not defined, is there a way to accomplish using this
variable for other parts of my code?
The key here is that s
is only defined in one branch of the
if-statement (which has 3 paths, BTW, counting the omitted āelse do
nothingā at the bottom). If your code took the other branch then s
wasnāt defined. If you try to access it unconditionally later, that will
work if it took the s=
branch and fail otherwise (because s
was not
defined).
It would be good to see the entire code, or at least enough code that it
can be run. For example, why just print true
in the first branch.
Instead of setting some variable etc?
Also note that s
isnāt a local of the for-loop. So if s
gets set on
one pass through the loop, it will still have that value on the next
pass. This isnāt something to fix, but definitely something to be aare
of.
If s
is only meant to have a value based on the current
loop
iteration then it should be reset in some way at the top of the loop.
Ignoring the loop itself, usually code why computes a value for some
variable should arrange that the variable has a value no matter how that
computation happens. Example:
if something:
s = 1
elif something_else:
s = 2
else:
s = 3
Here, there is no way to run the if-statement without setting s
to a
value.
If your objective is that s
should have a āsensibleā value for well
defined things but not for bad conditions (eg an invalid key
from your
for-loop), typically code would look like some variable on this:
s = None # distinct "invalid" value
if something:
s = 1
elif something2:
s = 2
etc. In this way s
is always set. It starts with a distinct value
for ānothing valid was foundā. In Python that is usually None
. Then
you have an if-statement to recognise various valid situations and to
compute s
accordingly.
Later you might go:
if s is None:
raise ValueError("no valid value!")
... use s to do stuff here ...
You may not raise an exception; what you do depends on your programme.
The point here is that you can recognise clearly that you have invalid
data and act accordingly.
Cheers,
Cameron Simpson cs@cskk.id.au