]
Since Python doesn't have a switch statement, you can make your own.
In Python you could do something like this though:
selector={
x<0 : 'return None',
0<=x<1 : 'return 1',
1<=x<2 : 'return 2',
2<=x<3 : 'return 3',
3<=x : 'return None'
}[a]
if a == 1, it would "return 1".
You seem to be a little bit confused, which is likely to make a newbie
really confused.
What is x in your example? Your dictionary's definition depends on multiple
expressions involving it -- you'd only get the result of selector == 'return
1' when a is 1 if 0 <= x < 1.
For instance:
.... x<0 : 'return None',
.... 0<=x<1 : 'return 1',
.... 1<=x<2 : 'return 2',
.... 2<=x<3 : 'return 3',
.... 3<=x : 'return None'
.... }
{False: 'return None', True: 'return 1'}
But:
.... x<0 : 'return None',
.... 0<=x<1 : 'return 1',
.... 1<=x<2 : 'return 2',
.... 2<=x<3 : 'return 3',
.... 3<=x : 'return None'
.... }
{False: 'return None', True: 'return 3'}
So looking up 1 in that dictionary would return whatever string was
associated with the key True (because 1 == True), which is entirely
dependent on the value of x when the dictionary was defined.
Also, your use of strings containing python statements is misleading --
retrieving a value from a dictionary doesn't implicitly execute it as a
string of Python source code too. Less confusing values would have been
'less than 0', 'between 0 and 1', and so on, because at least that is less
likely to confuse a newbie.
Finally, as someone else pointed out, often the best way to do a switch
statement in Python is not to be clever at all, but instead to just simply
do:
if x < 0:
return None
elif 0 <= x < 1:
return 1
elif 1 <= x < 2:
return 2
elif 2 <= x < 3:
return 3
else:
return None
Although that's a very contrived example (what's the point of doing that?)
-- more convincing would be something like:
if colour == 'red':
r, g, b = 255, 0, 0
elif colour == 'purple':
r, g, b = 255, 0, 255
# and so on ...
Which I think turns out to be a much better candidate for the dictionary
trick anyway:
rgbValues = {
'red': (255, 0, 0),
'purple': (255, 0, 255),
# ...
}
r, g, b = rgbValues[colour]
-Andrew.