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:
       print('true')
    elif (key['device']['profile']['id']) != 155975:
        s = (key['device']['id'])
        print(s)

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!

Thanks!

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

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