Define variable within elif statement

Hi all, I am trying to define a variable within an elif statment, but I suspect I messed up the syntax or worse, any help would be much appreciated.

My code is:

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, 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?

payload = {'device_id': s, 'id': '155975'}

Response:payload = {'device_id': s, 'id': '155975'} NameError: name 's' is not defined

Much appreciated!

If you would, please edit your post to use a code block (in the editor it’s the </> symbol, or you can type “```” before and after the code block) so that the indentation will be preserved. Since this is Python the indentation is very important for understanding how the code works. Thanks!

Apologies I have updated it - sorry about that!


So this code will work fine so long as you only reference s when the code path that set it is followed. If the other branch of the if/elif is followed, s will not be set, and any attempt to reference it will throw a NameError exception.

Also, while this is probably not your real code, there’s no need to use elif to just test the exact opposite condition you tested in if; else will work just fine there.

By Johan Mocke via Discussions on 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 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

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

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
    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
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.

Cameron Simpson

Thank you for your response, turns out I need more sleep - it was an indentation problem

payload = {'device_id': s, 'id': '155975'}

Was not correctly indented with the previous lines of code, facepalm!

Thanks again.

Thanks Cameron, I appreciate your detailed response, it was an indentation issue after all.

Thanks again, cheers!

1 Like