简体   繁体   中英

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. In the snippet below, although I expect the function to return "16" , actually "1500" is returned for some reason. 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. 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. 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. The remaining two characters ( "00" ) are disregarded, as the other string has run out of characters. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM