Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
>>> a = "end"
>>> if (a < "goodbye"):
print("end is less than goodbye")
elif (a > "goodbye"):
print("end is greater than goodbye")

end is less than goodbye
>>>

Python compares the values "end" and "goodbye" and determines which one is “greater.” Since
the string value "end" would come before "goodbye" in a sort method, it is considered “less
than” the "goodbye" string.


Now, try this example:


Click here to view code image


>>> a = "End"
>>> if (a < "goodbye"):
print("End is less than goodbye")
elif (a > "goodbye"):
print("End is greater than goodbye")

End is less than goodbye
>>>

Changing the capitalization of "End" still makes it less than "goodbye".


Next, compare the same word capitalized and in all lowercase letters:


Click here to view code image


>>> if (a == "end"):
print("End is equal to end")
elif (a < "end"):
print("End is less than end")
elif (a > "end"):
print("End is greater than End")

End is less than end
>>>

The capitalized version of the string evaluates to be less than the lowercase version. This is an
important feature to know when comparing string values in Python!


List and Tuple Comparisons


Python allows you to compare objects that contain multiple values, such as lists and tuples. In this
example, Python considers the list stored in the a variable less than the list stored in the b variable:


Click here to view code image


>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> if (a < b):
print("a is less than b")
elif (a > b):
print("a is greater than b")
Free download pdf