Is it bad practise to assign variables in an if statement and not use each variable if that part of the if statement is called?
For example in the following code I have two code option. Option 1 if trigger == ‘1’ or if trigger == ‘2’ then variable y will be unused as it is only needed if trigger == ‘4’ or if trigger == ‘5’. Option 2 is longer, but fixes this.
# option 1
if trigger == '1' or trigger == '4':
x = int(start)
y = int(s1)
elif trigger == '2'or trigger == '5':
x = int(s1)
y = int(s2)
elif trigger == '3':
x = int(s2)
# option 2
if trigger == '1' or trigger == '4':
x = int(start)
elif trigger == '2'or trigger == '5':
x = int(s1)
elif trigger == '3':
x = int(s2)
if trigger == '4':
y = int(s1)
elif trigger == '5':
y = int(s2)
My question is which one is correct and which one should I use?
Thanks.
Update –
So is it ok to set a variable and not use it if that part of the if function (in this case) is called? It is not bad practice or lead to memory issues etc. Thanks.
if trigger in ('1', '4'):, however, it's more pythonic.if trigger in '14'does the same thing and requires fewer keystrokestrigger == "14".trigger=='14'is not a requirement in this problem; and if were, I would suggestif trigger in '1 4 14'.split(). It still takes fewer keystrokes and makes it easier to add more trigger values to check against.