Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if with range
#1
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
Reply
#2
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)
Reply
#3
Wouldn't
1 <= a <= 200
check if a is a number between 1 and 200? And if you need to check only integers, a in range(1, 201) might work...
Reply
#4
(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')
Reply
#5
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
Reply
#6
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
Reply
#7
that's really good point which I overlooked
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020