编写这一小段 Python 代码的更有效方法是什么?

发布于 2024-10-19 09:07:50 字数 532 浏览 1 评论 0原文

我一直在阅读一本Python入门书,并且一直在尝试编写一小段代码来接受用户输入,检查以确保它可以转换为int并检查它是否高于49152。

我我知道有一种更简单的方法可以做到这一点,但我无法弄清楚。

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

check = True
while check == True:
    check = False
    try:
        port_number = int(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): ") 

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 = int(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): ") 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦屿孤独相伴 2024-10-26 09:07:50

无论如何,您拥有的功能在功能上都不正确。考虑一下如果有人先输入“123”,然后输入“abc”。 123 将使它们通过 while check 块,但是当它们到达 while while 49152 块没有检查。

这是我想到的(我不做Python,我只是根据你现有的代码破解它......)

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

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
眼泪都笑了 2024-10-26 09:07:50

如果将代码包装在函数中,则可以避免使用 check 标志:

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

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
笑,眼淚并存 2024-10-26 09:07:50
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)
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)
擦肩而过的背影 2024-10-26 09:07:50
n = 0

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

print "ok!"
n = 0

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

print "ok!"
一绘本一梦想 2024-10-26 09:07:50

不使用异常处理的变体

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

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
吹泡泡o 2024-10-26 09:07:50
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): ")

仅当 not port.isdigit() 为 False 时才会执行 int(port) 调用 ->端口包含数字。这是因为只有当第一个操作数为 False 时,才会计算 or 运算符的第二个操作数。

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.

墨落画卷 2024-10-26 09:07:50

我试图避免代码重复,并通过这种再现使事情变得更加Pythonic。请注意,我没有“例外:”,而是专门捕获 ValueError。人们经常忘记“除了:”也会捕获 SyntaxError 异常,这可能会使寻找愚蠢的拼写错误变得极其令人沮丧。我假设这里的端口号是 TCP 或 UDP 端口号,因此请确保它也小于 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文