Reputation: 79
I am trying to write a program in Python to check whether a number is in a given range and I want it to print a message when it's not. However, the following code I have come up with fails to print such a message (it works for the first two conditions, but not the third). I'd appreciate if someone could point out if there is a mistake in my code and also if there is a more efficient way to write it.
def range(a,b,n):
if b > a:
if(n>=a) and (n<=b):
print(n,"is within the range",a,"-",b)
elif b < a:
if(n>=b) and (n<=a):
print(n,"is within the range",a,"-",b)
else:
if (n>a,b) or (n<a,b):
print(n, "is not within the range", a,"-",b)
When I test the code with
range(2,8,300)
it prints nothing when it should print 300 is not within the range 2 - 8
.
Upvotes: 0
Views: 3524
Reputation: 316
if 8 > 2:
is true, so it goes inside and the nested if 300>=2 and 8<=300
condition
fails and exits. So, it never goes to else
loop.
Also, if (n>a,b) or (n<a,b)
this always returns True
. Since ("anything..")
becomes tuple and it's always True.
This works fine.
def fun(x,y,z):
x , y = min(x,y), max(x,y)
if z >= x and z <= y:
print(z," is within the range",x,"-",y)
else:
print(, "is not within the range", x,"-",y)
Upvotes: 1
Reputation: 16782
You need a interval comparison:
def range(a,b,n):
if a <= n <= a:
print(n,"is within the range",a,"-",b)
else:
print(n, "is not within the range", a,"-",b)
range(2,8,300)
OUTPUT:
300 is not within the range 2 - 8
OR alternatively:
def check_range(a,b,n):
isRange = range(min(a,b),max(a,b))
if n in isRange:
print(n, "is within the range", a, "-", b)
else:
print(n, "is not within the range", a, "-", b)
check_range(5,2,4)
OUTPUT:
4 is within the range 5 - 2
PS. I would not encourage using the Python built-in function
range()
as your custom function name.
Upvotes: 1
Reputation: 672
def range(a,b,n):
if a < b:
if n >= a:
if n <= b:
print(n,"is within the range",a,"-",b)
else:
print(n, "is not within the range", a,"-",b)
else:
print(n, "is not within the range", a,"-",b)
if a > b:
if n <= a:
if n >= b:
print(n,"is within the range",a,"-",b)
else:
print(n, "is not within the range", a,"-",b)
else:
print(n, "is not within the range", a,"-",b)
This should work.
EDIT: Modified the code. This will also test the cases involving negative numbers and zero.
Upvotes: 2
Reputation: 6404
You can try this:
def range(a, b, n):
if a <= n <= b:
print(n, "is within the range", a, "-", b)
else:
print(n, "is not within the range", a, "-", b)
Update:
def range(a, b, n):
if a > b:
if a>=n and b<=n:
print(n, "is within the range", a, "-", b)
else:
print(n, "is not within the range", a, "-", b)
else:
if a <= n <= b:
print(n, "is within the range", a, "-", b)
else:
print(n, "is not within the range", a, "-", b)
Then
>>> range(2, 8, 300)
300 is not within the range 2 - 8
>>> range(2, 8, 5)
5 is within the range 2 - 8
Upvotes: 1