through the different types of comparisons that are available in your Python scripts.
Numeric Comparisons
The most common type of comparisons have to do with comparing numeric values. Python provides a
set of operators for performing numeric comparisons in your if statement conditions. Table 6.1
shows the numeric comparison operators that Python supports.
TABLE 6.1 Numeric Comparison Operators
The comparison operators return a logical True value if the comparison succeeds and a logical
False value if the comparison fails. For example, the following statement:
Click here to view code image
if (x >= y): print("x is larger than y")
executes the print() statement only if the value of the x variable is greater than or equal to the
value of the y variable.
Watch Out!: The Equality Comparison Operator
Be careful with the equal comparison! If you accidentally use a single equal sign, it
becomes an assignment statement and not a comparison. Python processes the
assignment and then exits with a True value all the time. That’s probably not what you
want to do.
String Comparisons
Unlike numeric comparisons, string comparisons can sometimes be a little tricky. While comparing
two string values for equality is easy:
Click here to view code image
x = "end"
if (x == "end"): print("Sorry, that's the end of the game")
trying to use a greater-than or less-than comparison in strings can get confusing. When is one string
value greater than another string value?
Python performs what’s called a lexicographical comparison of string values. This method converts
letters in the string to the ASCII numeric equivalent and then compares the numeric values.
Here’s a test string comparison:
Click here to view code image