Good Day,
I want to check if any of this variable over 200 must print not within range can someone help me how can I do it
a = 12
b = 30
c = 50
# testing if variables a,b,c within the range
for i in range(1,200):
if a == i:
continue
elif b == i:
continue
elif c == i:
print('a , b , c within the range')
else:
print('Not within the range')
Moderator: nilamo: adding code tags
Do you have to actually iterate over the list? Because you can use the
in
operator with ranges, just like with dicts and lists.
a = 12
items = range(1, 200)
print(a in items)
(Mar-08-2017, 08:36 PM)Federer Wrote: [ -> ]I want to check if any of this variable over 200 must print not within range
If the only necessary check is whether any variable is (not) above 200, maybe this is sufficient:
a = 12
b = 30
c = 50
# testing if variables a,b,c within the range
if a <= 200 and b <= 200 and c <= 200:
print('a , b , c within the range')
else:
print('a or b or c not within the range')
a = 12
b = 30
c = 50
check_range = range(1,201)
# using comprihension
if all(x in check_range for x in (a,b,c)):
print 'all variables between 1 and 200'
else:
print 'not all variables between 1 and 200'
# using map and lambda
if all(map(lambda x: x in check_range, (a,b,c))):
print 'all variables between 1 and 200'
else:
print 'not all variables between 1 and 200'
if you have some iterable (list, tuple, etc.) you can easily substitute (a,b,c) for that iterable
I would be rather restrained when using range(a, b) to check if some number is between a and b. For python 2 it could be really atracious - what will happen if OP would want to check not the range 1 to 200, but the range 1 to 2000000000? And while for python 3 it works well, I still see it working well due to a "internal trick" and not working as intended ("testing for membership").
When python3 interprets x in range(a, b)
and x is integer, then range's __contains__() method does not even try to use the range as an iterable/sequence/whatever, instead of it just checks a <= x < b (for step != 1 constraints would be different). So why use x in range(a, b) instead of checking these conditions directly? And if you need to check if x is an integral, then you should check it anyway (except "tiny" ranges) - try 7.5 in range(0, 1000000000).
Disclaimer: as quite often, it is possible that I dont know what I am talking about
that's really good point which I overlooked