Python 3:验证端口号(1-65535之间的整数)

时间:2018-03-18 17:55:31

标签: python

我是Python新手并尝试验证给定的端口号是否有效。

第一次尝试

PortNumber = input("Enter a port number: ")
if PortNumber.isdigit() == True:
   print("This is a VALID port number.")
else:
   print("This is NOT a valid port number.")

输出

C:\> python test.py
Enter a port number: a
This is NOT a valid port number.

C:\> python test.py
Enter a port number: -1
This is NOT a valid port number.

C:\> python test.py
Enter a port number: 8
This is a VALID port number.

C:\> python test.py
Enter a port number: 88888
This is a VALID port number.

C:\>

此代码的唯一问题是端口号必须是1-65535之间的整数。

第二次尝试

PortNumber = int(input("Enter a port number: "))
if 1<= PortNumber <= 65535:
    print('This is a VALID port number.')
else:
    print('This is NOT a valid port number.')

输出

C:\> python test2.py
Enter a port number: 65535
This is a VALID port number.

C:\> python test2.py
Enter a port number: 65536
This is NOT a valid port number.

C:\> python test2.py
Enter a port number: -1
This is NOT a valid port number.

C:\> python test2.py
Enter a port number: a
Traceback (most recent call last):
  File "test2.py", line 1, in <module>
    PortNumber = int(input("Enter a port number: "))
ValueError: invalid literal for int() with base 10: 'a'

C:\>

我设法过滤掉第二段代码中1-65535之间的数字,但a字符还有另一个问题。

如何在代码中结合两种想法?

5 个答案:

答案 0 :(得分:3)

你可以尝试

try:
    port = int(input("Enter a port number: "))
    if 1 <= port <= 65535:
        print("This is a VALID port number.")
    else:
        raise ValueError
except ValueError:
    print("This is NOT a VALID port number.")

答案 1 :(得分:1)

您可以将两种方法结合起来:

PortNumber = input("Enter a port number: ")
if PortNumber.isdigit() and 1 <= int(PortNumber) <= 65535:
   print("This is a VALID port number.")
else:
   print("This is NOT a valid port number.")

答案 2 :(得分:1)

您可能想要这样做:

while True:
    try:
        PortNumber = int(input("Enter a port number: "))
    except ValueError:
        print("Error: expect an integer. Try again.")
        continue
    else:
        break
if 1 <= PortNumber <= 65535:
    print('This is a VALID port number.')
else:
    print('This is NOT a valid port number.')

while循环不允许用户进一步输入整数。此外,这种方法无需is_digit()

答案 3 :(得分:1)

进一步构建我可能会将可读性条件分开:

PortNumber = input("Enter a port number: ")

cond1 = PortNumber.isdigit()                # True/False
cond2 = (1 <= int(PortNumber) <= 65535)     # True/False

if cond1 and cond2:
   print("This is a VALID port number.")
else:
   print("This is NOT a valid port number.")

答案 4 :(得分:0)

您的解决方案不检查输入float或其他某种数据类型的条件

PortNumber = input("Enter a port number: \n")

if not(type(PortNumber) == int): 
    print("This is NOT a valid port number.")
elif 1<= PortNumber <= 65535:
    print('This is a VALID port number.')
else:
    print("This is NOT a valid port number.")