Home > Software design >  How to have code toggle between on and off states depending on current state?
How to have code toggle between on and off states depending on current state?

Time:06-02

Apologies for the title I am not really sure exactly what the name of what I am looking for is.

I have an NFC reader that accesses Spoti py and the Spotify Web API. I wish to use the same NFC card to toggle shuffle on/off.

if (uid == 123456789):
     sp.shuffle(state=True, device_id=DEVICE_ID)

The code above will turn shuffle on however when I now scan the card again I want it to disable shuffle. Essentially needing the code to read 'if card 123456789 is scanned turn shuffle on, however if shuffle is already on turn it off.

CodePudding user response:

maybe assign state to state variable, and for every scan change the state by using not:

state = False

while scanning:
    if (uid == 123456789):
        state = not state
        sp.shuffle(state=state, device_id=DEVICE_ID)

CodePudding user response:

if the current boolean state is available (for example under sp.shuffle) i would rather do like:

if (uid == 123456789):
     sp.shuffle(state=!sp.shuffle, device_id=DEVICE_ID)

In this way you always force it to change to the opposite boolean state.

  • Related