Chanヨネ
Chanヨネ

Reputation: 829

Variable >=(range)

Im trying to change what map is displayed when a requirement is met. I want to use a range on the elif statements to save some time.

curmov changes every turn in a range of 0-31

map1(),2,3 are ASCII maps

def curmap():
    global curmov
    if curmov <=9:
        mapNow = map1()
    elif curmov (10,24):
        mapNow = map2()
    elif curmov (25,30):
        mapNow = map3()

Upvotes: 0

Views: 82

Answers (1)

abarnert
abarnert

Reputation: 366073

I'm not 100% sure what curmov(10,24) is supposed to mean, but I suspect it's this:

10 <= curmov < 24

… or, equivalently:

curmov in range(10, 24)

(Note to any future readers using Python 2.x: don't use the second one. In Python 2.x, that will create a list of 14 numbers just to compare them one by one against curmov, which would be silly. In Python 3.x, it creates a range object, which can handle this instantaneously.)


Note that I'm using 10 <= curmov < 24. That's called a "half-open" range—the left half is "closed", because 10 is part of the range, while the right half is "open", because 24 is not. In Python, range(10, 24) checks the same thing, because all ranges are half-open in Python. If you want an "open" range (neither 10 nor 24 count as part of it) or a "closed" range (both 10 and 24 count), the first one is easy to change by just changing the <= or < appropriately; the second one, you have to add a +1 or -1 somewhere.


However, if your ranges aren't supposed to overlap or have any gaps, it may be simpler and more readable (and even more robust, because there's no chance for accidental off-by-one overlaps and gaps) to just do this:

if curmov <= 9: blah
elif curmov <= 24: bleh
elif curmov <= 30: blih
else: bluh

Upvotes: 3

Related Questions