[英]Wrote a function to determine if a number is a positive integer and it returns True for negative numbers
I defined the following function to test if an input is a positive int.我定义了以下函数来测试输入是否为正整数。 I plan on using eval(raw_input("...")) so that's why the try-except part is there:我计划使用 eval(raw_input("...")) 所以这就是 try-except 部分存在的原因:
def is_ok(x): # checks if x is a positive integer
is_int = False
is_pos = False
try:
if type(eval(x)) == int:
is_int = True
if x > 0:
is_pos = True
else:
pass
else:
pass
except NameError:
is_int = False
print "not even a number!"
return is_int, is_pos
if I try to pass a positive int it would return True, True as expected.如果我尝试传递一个正整数,它将按预期返回 True,True。 It returns False, False and the error message for a non-number.它返回 False、False 和非数字的错误消息。
However, for negative numbers it still returns True for checking if it's positive.但是,对于负数,它仍然返回 True 以检查它是否为正数。 For example, adding this after the function :例如,在函数之后添加:
is_int, is_pos = is_ok("-9")
print is_int, is_pos
running prints: True True运行打印:真真
Can't understand why that is and would love your help.不明白为什么会这样,希望得到你的帮助。 Even if there are more efficient ways to accomplish this, I'd still like to understand why it produces True True.即使有更有效的方法来实现这一点,我仍然想了解它为什么会产生 True True。 Thanks!谢谢!
(This is somewhat of a followup to: Python: How do I assign 2 values I return from a function with 1 input as values outside the function? ) (这在某种程度上是对以下内容的跟进: Python:如何分配从具有 1 个输入的函数返回的 2 个值作为函数外部的值? )
Shorten it down a bit:缩短一点:
def is_ok(x):
is_int = False
is_pos = False
try:
x = float(x)
# Check if the number is integer or not
is_int = x.is_integer()
if x > 0:
is_pos = True
except ValueError:
print("not even a number!")
return is_int, is_pos
To explain how this works, you can pass a string to int()
to convert this to an integer.为了解释这是如何工作的,您可以将字符串传递给int()
以将其转换为整数。 However, passing an invalid string (like foo
) will raise a ValueError
.但是,传递无效字符串(如foo
)将引发ValueError
。 We can catch that and display our "not even a number!"
我们可以抓住它并显示我们的"not even a number!"
message to the user.给用户的消息。 Much safer than using eval()
.比使用eval()
安全得多。
Try not to use eval()
unless you absolutely trust the input.除非您绝对信任输入,否则尽量不要使用eval()
。
Removing all the variables you can also make it:删除所有变量,你也可以做到:
def is_ok(x):
try:
# Check if is an integer and greater than 0
return float(x).is_integer(), float(x) > 0
except ValueError:
print("not even a number!")
return False, False
Your original problem was it was returning True, True
for even negative numbers.您最初的问题是它返回True, True
即使是负数也是True, True
。 The problem here is that whilst you were using type(eval(x)) == int
you were then not making x
an integer object.这里的问题是,当您使用type(eval(x)) == int
您并没有将x
设为整数对象。 This then has an unexpected effect when you try and compare a string to an integer later on ( if x > 0
):当您稍后尝试将字符串与整数进行比较时( if x > 0
),这会产生意想不到的效果:
In [9]: "twenty" > 0
Out[9]: True
You can read more about this strange behaviour in this very detailed answer .您可以在这个非常详细的答案中阅读有关这种奇怪行为的更多信息。
If you were to redefine x
as your variable:如果您要将x
重新定义为变量:
try:
x = eval(x)
if type(x) == int:
Then when you made the comparison it would behave better and return True, False
for "-9"
.然后,当您进行比较时,它会表现得更好,并为"-9"
返回True, False
。
This all seems needlessly complicated, and using eval
on raw_input
is a security risk - the user can enter anything they like.这一切似乎都是不必要的复杂,并且在raw_input
上使用eval
存在安全风险 - 用户可以输入他们喜欢的任何内容。
Instead, try something like:相反,请尝试以下操作:
def is_ok(s):
try:
i = int(s)
except ValueError:
return False, False
else:
return True, i >= 0
Example inputs and outputs:示例输入和输出:
>>> for s in ["foo", "9", "-9"]:
print s, is_ok(s)
foo (False, False)
9 (True, True)
-9 (True, False)
Your error is here:你的错误在这里:
if x > 0:
Remember x
is still a string, and in Python 2.x all strings will compare > 0
.记住x
仍然是一个字符串,在 Python 2.x 中所有字符串都会比较> 0
。
>>> def is_int_positive(n):
... try:
... if n == 0:
... return True, 'Positive'
... elif max(0,int(n)):
... return True, 'Positive'
... else:
... return True, 'Negative'
... except:
... return False, 'Error'
...
>>> for i in [1, 0, -23, 23, 'a']:
... print i, is_int_positive(i)
...
1 (True, 'Positive')
0 (True, 'Positive')
-23 (True, 'Negative')
23 (True, 'Positive')
a (False, 'Error')
>>>
why not make it simple为什么不简单点
def is_positive(number):
if number > 0:
return True
else:
if number <= 0:
return False
def is_ok(x):
try:
return type(x)==int, int(x)>0
except ValueError:
return False, False
Or:或者:
def is_ok(x):
try:
return type(x)==int, 'Positive' if int(x)>0 else 'Negative'
except ValueError:
return False, 'Neither'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.