开发者

More efficient way to write this small bit of Python code?

I've been going through a beginning Python book, and I've been trying to write a small block of code that will take users input, check to make sure it can be converted to an int and check if it's higher than 49152.

I know there's an easier way to do this, but I can't get my mind to figure it out.

port_input = raw_input("port(number must be higher than 49152: ")

check = True
while check == True:
    check = False
    try:
        port_number = in开发者_C百科t(port_input)
    except:
        port_input = raw_input("port(number must be higher than 49152: ")
        check = True

while int(port_input) < 49152:
    port_input = raw_input("Please enter a higher number(hint: more than 49152): ") 


What you have isn't functionaly correct anyway. Consider if someone puts "123" then "abc". The 123 will get them through the while check block, but when they get to the while < 49152 block there's no checking.

Here's what I come up with (I don't do python, I just hacked it in based on your existing code...)

check = True
while check :
    port_input = raw_input("port(number must be higher than 49152: ")
    try:
        port_number = int(port_input)
        check = (port_number < 49152)
    except ValueError:
        check = True


You can avoid the check flag if you wrap your code in a function:

def get_port():
    while True:
        port =  raw_input("port (number must be higher than 49152): ")
        try:
            port = int(port)
        except ValueError:
            continue
        if port > 49152:
            return port


def get_input(msg = "port(number must be higher than 49152: "):
    port_input = raw_input(msg)
    try :
        if int(port_input) < 49152:
            return get_input("Please enter a higher number(hint: more than 49152): ")
    except ValueError:
        return get_input()
    return int(port_input)


n = 0

while n < 49152:
    try:
        n=int(raw_input("enter number heghier than 49152->"))
    except: 
        print "not integer!"

print "ok!"


variant without using exception handling

def portInput(text):
    portInput.port_value = 0
    while True:
        port_input = raw_input(text)
        if not port_input.isdigit(): yield "port must be numeric"
        else:
            portInput.port_value = int(port_input)
            if portInput.port_value <= 49152: yield "number must be higher than 49152"
            else: return

for error in portInput("port(number must be higher than 49152): "):
    print error

print "entered port: %d" % portInput.port_value


port = raw_input("port(number must be higher than 49152): ")
while not port.isdigit() or int(port) <= 49152:
    print("port must be a number > 49152")
    port = input("port(number must be higher than 49152): ")

The int(port) call is only done when not port.isdigit() is False -> port contains of digits. This is because the second operand for the or operator is only evaluated if the first is False.


I tried to avoid code duplication and make things a bit more pythonic with this rendition. Notice that I do not 'except:' but instead specifically catch ValueError. Often people forget that 'except:' also catches the SyntaxError exception which can make hunting down a stupid typo extremely frustrating. I assumed the port number here is a TCP or UDP port number and thus make sure it is also less than 65536.

have_valid_input = False

while not have_valid_input:
    unsafe_port = raw_input('port: ')
    try:
        port_number = int(unsafe_port)
    except ValueError:
        pass
    else:
        if port_number > 49152 and port_number < 65536:
            have_valid_input = True

    if not have_valid_input:
        print 'Invalid port'

print 'port', port_number
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜