Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Thursday, May 17, 2012

Toggling a value using dictionary

There are a number of ways to toggle a value between two states but I picked this one up from CS212 and it's using a datatype instead of writing a function.
#dictionary used to toggle some variable state
toggleColor = {'blue': 'red', 'red': 'blue'}
currentColor = 'blue'
print currentColor
currentColor = toggleColor[currentColor]
print currentColor
currentColor = toggleColor[currentColor]
print currentColor

blue
red
blue

Below solution was the one I used for switching between states 0 and 1. But using a dictionary is a nobrainer and you can even give the dictionary a function alike name.
#possible_states = [0,1]
currentstate = 0
print currentstate
currentstate = abs(currentstate - 1)
print currentstate
currentstate = abs(currentstate - 1)
print currentstate

0
1
0

No comments:

Post a Comment