Reputation: 83
I am trying to print all values within a user specified range. However when I enter numbers the program does not print the values.
print "This module will return all numbers in a specified range."
v = range(-100000, 100001)
lo = int(raw_input("Please enter the beginning of the range:"))
hi = int(raw_input("Please enter the end of the range: "))
def filter_range():
if lo < v[0] and hi > v[-1]:
print v[lo: hi]
elif lo < v[0]:
print "That is out of range."
if hi > v[-1]:
print "That is out of range."
pass
if __name__ == '__main__':
filter_range()
Upvotes: 0
Views: 67
Reputation: 122061
When you create your range v
, the indices for items start at 0, not -100000. Therefore, when you
print v[lo: hi]
you are not actually printing the values asked for. For example, if I ask for 0 to 10, I get -100000 to -99990. Why not create the range
only when needed?
print(list(range(lo, hi)))
This saves on all the memory you fill up with 200002 integers, and you don't need to test if hi
and lo
are in some range, which was causing your other problem (per samrap's answer).
Note that in earlier versions of 2.x, you will need to write print range(lo, hi)
.
Upvotes: 3
Reputation: 1096
You don't want to use the values given as the indices per your own instructions. Nor should you store such a large vector. See the revised code below.
print "This module will return all numbers in a specified range."
allowed_lo = -100000
allowed_hi = 100000
lo = int(raw_input("Please enter the beginning of the range:"))
hi = int(raw_input("Please enter the end of the range: "))
def filter_range():
if lo < allowed_lo or hi > allowed_hi:
print "That is out of range."
else:
return range(lo, hi+1)
if __name__ == '__main__':
print filter_range()
Something that is a little more fun would be to use list comprehension to do this.
v = range(-100000,100001)
lo = int(raw_input("Please enter the beginning of the range:"))
hi = int(raw_input("Please enter the end of the range: "))
def filter_range():
if lo < allowed_lo or hi > allowed_hi:
print "That is out of range."
else:
print [x for x in v if lo <= x <= hi]
if __name__ == '__main__':
print filter_range()
Upvotes: 1
Reputation: 5673
Pretty sure you want to change this line:
if lo < v[0] and hi > v[-1]:
print v[lo: hi]
To this:
if lo > v[0] and hi < v[-1]:
print v[lo: hi]
Output:
[-99999, -99998, -99997, -99996, -99995, -99994, -99993...]
Upvotes: 1