Can anyone explain how does Python perceives colors? I saw the following line of code in the course:
print("Yellow">"Cyan" and "Brown">"Magenta")
With the output ‘False’
If we would change the code to:
print("Yellow">"Cyan" and "Brown"<"Magenta")
Then the output would be ‘True’
How does Python assumes what’s > and what’s < ?
///
Screenshot of console from the course
It’s part of the Google IT Automation with Python Professional Certificate
Crash Course on Python
CodePudding user response:
In your example, you are comparing strings without any attached meaning from the perspective of the Python interpreter. This thread nicely demonstrates how strings are compared.
CodePudding user response:
Whats happening
When comparing Strings with ">" or "<", the individual characters are compared to each other.
If one character comes before the other in lexicographical order, it is smaller.
If both characters are the same, the next character of the string is compared.
e.g.:
"Yellow" > "Cyan" == true
because "Y" comes after "C" in the alphabet.
The same goes for
"Brown" > "Magenta" == false
because "B" comes before "M" and is therefore smaller.
Why it works like this
When comparing characters, the ascii values of the characters are compared.
Hence "B" (which is interpreted as '66') is smaller then "M" ('77').
You can check this yourself with:
print(chr(66)) # Will output 'B'