2014-03-04 346 views
0
def main(): 
port = 10000000 
portChecked = portChecker(port) 
if portChecked is portChecked: 
    print '%d is in the portlist' % port 

def portChecker(x): 
portCheck = range(65565) 
portList = list(portCheck) 
portCast = x 

if portCast in portList: 
    return 
else: 
    print '%d is not in the list' % portCast 

if __name__ == '__main__':main() 

开始学习Python,与暴力蟒蛇电子书,以为我会写一个简单的函数来检查正在由用户输入端口(或静态值)使用Python函数返回和比较

如果端口在该范围内,程序将打印出列表中的%d,但是就像这里一样,如果它在范围之外,那么两个打印语句都会执行。

我是否错过了函数调用,返回语句的使用或者我是否以错误的方式查看了这些内容。

谷歌搜索,似乎没有给出类似的解决方案,大多数教程使用int或字符串。

所有帮助表示赞赏。

+1

'如果portChecked是portChecked:'永远是真正的 –

+1

创建的65565个整数整个名单只是为了检查一个数字是否在一个区间是错误的。使用这个:'如果0

回答

3

有几个问题与您的代码:

  • portChecker总是返回None
  • portChecked is portChecked始终计算为True
  • 通常它不是有(部分)的输出中的一个好主意检查功能

试试这样:

def checkPort(x): 
    portList = range(65565) 
    return x in portList 

port = 10000 
if checkPort(port): 
    print '%d is in the port list' % port 
else: 
    print '%d is NOT in the list' % port 

此外,请注意端口是from 1 to 65565,所以您应该检查它是否在range(1, 65565 + 1)。但是,除非您打算检查端口是否已经预留,否则检查1 <= x <= 65565是否更快更明确。

+0

我使用另一个函数的argparse传递端口值。以为我会使用这种形式,而不是复制整个脚本。感谢您的帮助:) – choczy

0

我不知道为什么这还没有提到。

您不需要创建值列表(整数)来检查此范围内是否有某个值。 你可以这样写:

def check_port(port): 
    return 0 <= port <= 65565 
+1

实际上,我提到了这一点(但只是顺带一提),但您好好强调这一部分。 ;-) –

+0

顺便说一句,我不知道OP是否知道'range(65565)'不包含'65565'。 –

+0

AH,看起来简单得多,这是我的第一语言,没有意识到你可以使用这样的回报。 – choczy