我正在尝试用Python编写程序,以检查数字是否在给定范围内,我希望它在不存在数字的情况下显示一条消息。但是,我提供的以下代码无法打印这样的消息(它适用于前两个条件,但不适用于第三个条件)。如果有人指出我的代码有错误以及是否有更有效的编写方法,我将不胜感激。
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)
当我使用来测试代码时
range(2,8,300)
它应该打印300 is not within the range 2 - 8
时不打印任何内容。
答案 0 :(得分:2)
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)
这应该有效。
编辑:修改了代码。这还将测试涉及负数和零的情况。
答案 1 :(得分:1)
public class InputStreamResource extends AbstractResource {
//...
@Override
public boolean isOpen() {
return true;
}
//...
}
是对的,因此它进入内部并且嵌套了if 8 > 2:
条件
失败并退出。因此,它永远不会进入if 300>=2 and 8<=300
循环。
此外,else
始终返回if (n>a,b) or (n<a,b)
。由于 True
成为元组,并且始终为True。
这很好。
("anything..")
答案 2 :(得分:1)
您需要进行间隔比较:
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)
输出:
300 is not within the range 2 - 8
或者:
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)
输出:
4 is within the range 5 - 2
PS。我不鼓励使用Python内置函数
range()
作为您的自定义函数名称。
答案 3 :(得分:1)
您可以尝试以下方法:
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)
更新:
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)
然后
>>> range(2, 8, 300)
300 is not within the range 2 - 8
>>> range(2, 8, 5)
5 is within the range 2 - 8