Python测试整数是否在一定范围内

2024-09-30 01:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个程序来测试一个数字是否在某个范围之外。。。我做错什么了?。。你知道吗

def outside(testnum, beginRange, endRange):
   if testnum <= beginRange:
        return false
   if testnum >= endRange:
        return false

Tags: 程序falsereturnifdef数字outsidetestnum
3条回答

你需要在底部返回true (还请注意,对于我来说,如果某个对象是beginRange或endRange,我会将其视为内部对象,因此我会执行<;and>;而不是<;=and>;=),因此。。。对于外部的东西,您可能希望返回true,否则返回false。(还要注意,它应该是False/True,而不是False/True)

一个简单的单行线可以在这里工作:

def inside(testnum, lowthreshold, highthreshold):
    return lowthreshold <= testnum <= highthreshold

def outside(testnum, lowthreshold, highthreshold):
    return not (lowthreshold <= testnum <= highthreshold)

编辑:意识到我指的是内部,而不是外部。更清楚了。你知道吗

false应该是False并且在末尾返回True,否则如果两个条件都是False,函数将返回None(默认返回值)。你知道吗

def outside(testnum, beginRange, endRange):
   if testnum <= beginRange:
        return False
   if testnum >= endRange:
        return False
   return True 

或者简单地说:

def outside(testnum, beginRange, endRange):
   return beginRange < testnum < endRange

相关问题 更多 >

    热门问题