编写这一小段 Python 代码的更有效方法是什么?
我一直在阅读一本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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
无论如何,您拥有的功能在功能上都不正确。考虑一下如果有人先输入“123”,然后输入“abc”。 123 将使它们通过
while check
块,但是当它们到达while
while
49152
块没有检查。这是我想到的(我不做Python,我只是根据你现有的代码破解它......)
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 thewhile < 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
标志:You can avoid the
check
flag if you wrap your code in a function:不使用异常处理的变体
variant without using exception handling
仅当
not port.isdigit()
为 False 时才会执行int(port)
调用 ->端口包含数字。这是因为只有当第一个操作数为 False 时,才会计算or
运算符的第二个操作数。The
int(port)
call is only done whennot port.isdigit()
is False -> port contains of digits. This is because the second operand for theor
operator is only evaluated if the first is False.我试图避免代码重复,并通过这种再现使事情变得更加Pythonic。请注意,我没有“例外:”,而是专门捕获 ValueError。人们经常忘记“除了:”也会捕获 SyntaxError 异常,这可能会使寻找愚蠢的拼写错误变得极其令人沮丧。我假设这里的端口号是 TCP 或 UDP 端口号,因此请确保它也小于 65536。
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.