Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写这一小块Python代码的更有效的方法是什么?_Python_Input - Fatal编程技术网

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

编写这一小块Python代码的更有效的方法是什么?,python,input,Python,Input,我一直在阅读一本Python入门书,我一直在尝试编写一小段代码,这些代码将接受用户的输入,检查以确保它可以转换为int,并检查它是否高于49152 我知道有一个更简单的方法,但我不能让我的头脑去想它 port_input = raw_input("port(number must be higher than 49152: ") check = True while check == True: check = False try: port_number =

我一直在阅读一本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): ") 
port\u input=raw\u input(“端口(数字必须大于49152:”)
检查=正确
当check==True时:
检查=错误
尝试:
端口号=int(端口号输入)
除:
端口输入=原始输入(“端口(编号必须大于49152:”)
检查=正确
当int(端口输入)<49152时:
端口输入=原始输入(“请输入更高的数字(提示:超过49152):”)

< /代码> 无论如何,你所拥有的功能并不正确。考虑是否有人把“123”加上“abc”。123将在检查< <代码>块时通过<代码>,但是当他们到达<代码>时<< 49152 < /Cord>块没有检查。

下面是我的想法(我不做python,我只是根据您现有的代码对其进行了黑客攻击…)

check=True
检查时:
端口输入=原始输入(“端口(编号必须大于49152:”)
尝试:
端口号=int(端口号输入)
检查=(端口号<49152)
除值错误外:
检查=正确
def get_输入(msg=“端口(数字必须大于49152:”):
端口输入=原始输入(msg)
尝试:
如果int(端口输入)<49152:
返回get_输入(“请输入更高的数字(提示:超过49152):”)
除值错误外:
返回get_输入()
返回int(端口输入)

我试图避免代码重复,并使用此格式副本让事情变得更像python。请注意,我没有“except:”而是专门捕获ValueError。通常人们忘记了“except:”还捕获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
have\u valid\u input=False
虽然没有有效的\u输入:
不安全\u端口=原始\u输入('端口:')
尝试:
端口号=int(不安全的端口)
除值错误外:
通过
其他:
如果端口号>49152且端口号<65536:
具有有效的\u输入=真
如果没有有效的\u输入:
打印“无效端口”
打印“端口”,端口号
n=0
当n<49152时:
尝试:
n=int(原始输入(“输入大于49152->”的数字)
除:
打印“非整数!”
打印“好!”

不使用异常处理的变体

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
def端口输入(文本):
portInput.port_值=0
尽管如此:
端口输入=原始输入(文本)
如果不是端口_input.isdigit():yield“端口必须是数字”
其他:
portInput.port_value=int(port_输入)

如果portInput.port_值将代码包装到函数中,则可以避免使用
检查
标志:

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
port=raw\u输入(“端口(编号必须大于49152):”)

而不是port.isdigit()或int(端口)端口包含个位数。这是因为
运算符的第二个操作数只有在第一个操作数为False时才会计算。

@nmichaels很好。正如我所说,我只是复制了他的代码并对其进行了调整。我将在中编辑它,因为这是一个适用于所有语言的好点!…修复了!对于不使用Python的人来说,这很好od:-)不过有两点-一个简单的'exception:'是非常糟糕的形式,它应该是'exception ValueError:'所以您只捕获您感兴趣的异常,而不掩盖您不期望的异常。我还将“check=(port_number<49152)”移动到“else:”try/except上的子句,因此您捕获的ValueError显然来自int(端口号)非常感谢。我没有花太多心思让它完全功能化,因为这只是我在学习Python时的一个短暂想法。但我知道必须有一种更有效的方法来编写它。@Downvoter-我很好奇为什么我会被否决。我总是乐于改进(包括我的答案和我自己作为一名开发人员),所以请让我知道它为什么是DV'd!:)它不应该是
return get_input()
所以你不会丢失返回值吗?我不是python爱好者,所以可能没有必要,这只是我脑海中闪现的东西。如果它真的像你描述的那样工作,你介意解释一下如何工作吗?谢谢!:我忘了返回!递归对我来说很难。它甚至不是在函数中,它只是我运行的一个代码块。我不喜欢它将使用,这是我想到并想解决的一个问题。我认为使用函数和递归比使用无限循环更简单。@fabio一个有趣的想法,但递归堆栈最终会溢出。如果用户从未输入正确的答案怎么办?不必输入时程序堆栈会溢出吗?:OI将放在这里对于您和所有回答者:除了(不是双关语,真的)在这里没有遇到的一些情况下。@delnan:很好的观点,相关的:'Exception'应该用于例外,而不是经常发生的错误。@payne:EAFP是常见的,被标准库接受和鼓励的(如果要验证字符串类型的int,而不通过
int
将其转换为int,并捕获异常,则必须自己滚动正则表达式或使用
str.isdigit
并禁止符号)在Python中。即使第一次尝试的结果很好,您的示例也会打印出
无效端口
。尽管我的答案获得了最多的赞成票,但我非常喜欢这一条。尽可能避免异常是一件好事!
n = 0

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

print "ok!"
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
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
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): ")