[英]Why does `n1 if eval(“n1<=n2”) else n2` always return `n1`?
I'm trying to write a function smaller_num(n1, n2)
which returns the smaller value of two parameters.我正在尝试编写一个 function small_num smaller_num(n1, n2)
,它返回两个参数的较小值。 In the snippet below, although I expect the function to return "16"
, actually "1500"
is returned for some reason.在下面的代码段中,虽然我希望 function 返回"16"
,但实际上由于某种原因返回了"1500"
。 What's wrong with the logic?逻辑有什么问题?
def smaller_num(n1, n2):
return n1 if eval("n1<=n2") else n2
print(smaller_num("1500", "16"))
Your use of eval()
is redundant.您对eval()
的使用是多余的。 Try simply简单尝试
def smaller_num(n1, n2):
return n1 if n1<=n2 else n2
It's now clear that现在很清楚了
print(smaller_num("1500", "16"))
amounts to总数是
"1500"<="16"
ie you are really comparing strings.即你真的在比较字符串。 This is done lexicographically (ie according to their position in the ASCII/Unicode table), character by character.这是按字典顺序(即根据 ASCII/Unicode 表中的 position)逐个字符完成的。 So though the first character are the same ( "1"
and "1"
), the second character ( "5"
vs. "6"
) is not "smaller or equal" for the first variable.因此,尽管第一个字符相同( "1"
和"1"
),但第二个字符( "5"
vs. "6"
)对于第一个变量来说不是“小于或等于”。 The remaining two characters ( "00"
) are disregarded, as the other string has run out of characters.剩下的两个字符( "00"
)被忽略,因为另一个字符串已经用完了字符。 An equivalent comparison is then "15"<="16"
, which also happens to be equivalent to 15<=16
as integers appear consecutively on the ASCII/Unicode table.一个等效的比较然后是"15"<="16"
,它也恰好等于15<=16
因为整数连续出现在 ASCII/Unicode 表上。
To do what you want, just use做你想做的事,只需使用
print(smaller_num(1500, 16))
You may even keep your original eval()
in smaller_num()
, though I don't see the point.您甚至可以将原始eval()
保留在smaller_num()
中,尽管我不明白这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.