使用Python函数返回和比较

2024-09-28 19:26:45 发布

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

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的时候,我想我应该写一个简单的函数来检查用户输入的端口(或者静态值)

如果端口在范围内,程序将打印出列表中的%d,但是像这里一样,如果端口在范围外,两个print语句都将执行。你知道吗

我是不是在函数调用、返回语句的使用上遗漏了什么,或者是我用错误的方式看待这个问题。你知道吗

google似乎没有给出类似的解决方案,大多数教程使用int或字符串。你知道吗

感谢所有的帮助。你知道吗


Tags: the端口inifismainportdef
2条回答

我不知道为什么还没提到这个。你知道吗

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

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

您的代码有一些问题:

  • portChecker总是返回None
  • portChecked is portChecked总是计算为True
  • 一般来说,在check函数中包含(部分)输出不是一个好主意

尝试以下操作:

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是否已被保留会更快更清晰。你知道吗

相关问题 更多 >