Reputation: 81
I suspect this question will have been asked before, so feel free to link, but I couldn't find it.
I want to write a program that will check if my variable a is between two certain numbers, otherwise check the next pair. IE in psuedocode:
Check if variable is between 1000 and 2000
If it is, do this.
Else, check if variable is between 2000 and 3000
If it is, do this.
Else check if variable is between 3000 and 4000
If it is, do this.
I suspect it's easy, but I really can't seem to figure it out. Any help would be appreciated.
Upvotes: 0
Views: 171
Reputation: 34007
You may need a list
to store the boundaries:
In [29]: rang = range(0, 5001, 1000)
...: foo = 1234
...: for i, v in enumerate(rang):
...: if v <= foo < rang[i+1]:
...: print (v, rang[i+1]), foo
...:
(1000, 2000) 1234
Upvotes: 0
Reputation: 1500
You don't need the second comparison all the time, since its implicitly satisfied because of the earlier comparisons:
if var < 1000:
doLower1000()
elif var < 2000:
doThis()
elif var < 3000:
doThat()
elif var < 4000:
doSomethingelse()
else:
doSomethingBigger4000()
Upvotes: 0
Reputation: 5652
variable = 1500
if 1000 < variable < 2000:
print ('1')
elif 2000 < variable < 3000:
print ('2')
elif 3000 < variable < 4000:
print ('3')
Upvotes: 1
Reputation: 599490
You can use chained comparisons:
if 1000 <= foo < 2000:
do_bar()
elif 2000 <= foo < 3000:
do_quux()
Upvotes: 2