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

(singke) #1
else:
print("It's not there!")
It's not there!
>>>

You can also add the not logical operator with the in comparison operator to reverse the result:


Click here to view code image


>>> if 7 not in tuple8:
print("It's not there!")
else:
print("It's there!")

It's there!
>>>

Sometimes adding the not logical operator to the comparison comes in handy, such as if you want to
reverse the order of the “then” and “else” code blocks to place the shorter block first before the
longer code block.


Finding the Number of Values in a Tuple


Python includes the len() function to allow you to easily determine how many data values are in a
tuple. Here’s an example of its use:


>>> len(tuple8)
10
>>>

Watch Out!: Referencing the Last Value in a Tuple
Be careful when you use the len() function with tuples. A common beginner’s
mistake is to think the value returned by len() is the index of the last data value in
the tuple. Remember that the tuple index starts at 0 , so the ending tuple index value is
one less than the value the len() function returns!

Finding the Minimum and Maximum Values in a Tuple


Python provides the min() and max() functions to give an easy way to find the smallest (min())
and largest (max()) values in a tuple, as in this example:


>>> min(tuple8)
1
>>> max(tuple8)
10
>>>

The min() and max() functions can also work with tuples that store string values. Python
determines the minimum and maximum values by using standard ASCII comparisons:


>>> min(tuple4)
'Friday'
>>> max(tuple4)
'Wednesday'
>>>
Free download pdf