+ 3

Why is this False in Python? print("3" < "10")

Hello I'm very new to all this. I'm going through a course and wondering why this code is false in Python. print("3" < "10") while this is true: print("3" < "4") I need help! Thank you! -Sam

17th Nov 2016, 5:56 AM
Sam
Sam - avatar
4 ответов
+ 4
Anything you put inside double quotes is a string So when you compare "3" < "10", it compares character by character and as 3 comes after 1 in ASCII, hence it is false whereas when you compare "3" < "4", it is true because 4 comes after 3. You can check the 'ord' function in python to get ASCII numbers.
17th Nov 2016, 8:09 AM
Ishpreet Singh Bindra
Ishpreet Singh Bindra - avatar
+ 2
Great Question! when you put the number betwwen "" it means that python is only look at the number of constituent ! Not size of the number !!! I don't know how to explain that for example we now that 3 is bigger than 2 so if we write ("3"<"22") or ("3"<"2222211") or .... all of them are false because there is no number that is bigger than 3 but if we write (3 < 2221) , now it's True because now python look at the size of the numbers *_* in example that you said ("3"<"10") is False because 1 and 0 or smaller than 3
17th Nov 2016, 6:48 AM
fazel
fazel - avatar
+ 2
nb: (i) when considering string comparison you should look up ASCII chart. (ii) don't compare string as a whole instead character by character question 1: print("3" < "10") you see if you compare two string of unequal length the shorter one will be increased by a space(s). ASCII value for 3 = 5 for 1= 49 for 0= 48 for space= 32 for 4=52 note: character will be compared similarly to a dictionary -> 3 vs 1 [3 is bigger] -> space vs 0 [space is smaller] since 3 is greater than 1 comparing space and 0 is then irrelevant. so ("3" < "10") is false ☑ question 2: print("3" < "4") character 3 [ASCII value 51] is less than character 4 [ASCII value 52]. so ("3" < "4") is True ☑ for ASCII chart visit http://ascii.cl/index.htm?content=mobile example: evaluate print("ant"<"and") print("an"<"ant") print("Zebra">"Elephant") print("ant">"Ant")
17th Nov 2016, 6:52 AM
CIVM
0
Exactly Fazel
21st Nov 2016, 12:26 AM
CIVM