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

(singke) #1
a is less than b
>>>

In the previous example, both lists are the same length. To see how Python handles comparing two
lists of different lengths, you can try this example:


Click here to view code image


>>> c = [7,8]
>>> if (a < c):
print("a is less than c")
elif (a > c):
print("a is greater than c")

a is less than c
>>>

Even though the c variable contains a shorter list, Python evaluates the a variable list to be less than
the c variable list.


Boolean Comparisons


Since Python evaluates the if statement condition for a logic value, testing Boolean values is pretty
easy:


Click here to view code image


>>> x = True
>>> if (x): print("The value is True")
The value is True
>>> x = False
>>> if (x): print("The value is True")
>>>

Setting a variable value directly to a logical True or False value is pretty straightforward.
However, you can also use Boolean comparisons to test other features of a variable.


If you set a variable to a value, Python also makes a Boolean comparison:


Click here to view code image


>>> a = 10
>>> if (a): print("The a variable has been set")

The a variable has been set
>>>

The same applies if you assign a string value to a variable:


Click here to view code image


>>> b = "this is a test"
>>> if (b): print("The variable has been set")

The variable has been set
>>>

However, if a variable contains a value of 0 , it evaluates to a False Boolean condition:


Click here to view code image

Free download pdf