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,但就像这里一样,如果它超出了范围,则两个print语句都将执行。
我是否遗漏了函数调用、返回语句的使用,还是以错误的方式看待这个问题。
谷歌似乎没有给出类似的解决方案,大多数教程使用int或字符串。
所有的帮助都是感激的。
发布于 2014-03-04 13:31:01
您的代码有几个问题:
portChecker总是返回NoneportChecked 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另外,请注意端口是从1到65565,所以您应该检查它是否在range(1, 65565 + 1)中。但是,除非您计划检查端口是否已被保留,否则检查1 <= x <= 65565是否已被保留会更快、更清晰。
发布于 2014-03-04 13:34:34
我不知道为什么还没提到这件事。
您不需要创建值列表(整数)来检查此范围内的某些值。你可以直接写:
def check_port(port):
return 0 <= port <= 65565https://stackoverflow.com/questions/22173059
复制相似问题