By Johan Mocke via Discussions on Python.org at 11Jul2022 22:34:
for key in question_access:
if (key[‘device’][‘profile’][‘id’]) == 155975:
elif (key[‘device’][‘profile’][‘id’]) != 155975:
s = (key[‘device’][‘id’])
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
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
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
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
s is only meant to have a value based on the
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:
s = 1
s = 2
s = 3
Here, there is no way to run the if-statement without setting
s to a
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
s = 1
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
you have an if-statement to recognise various valid situations and to
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.
Cameron Simpson firstname.lastname@example.org