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

(singke) #1

some other types of mathematical operators. Table 5.1 shows all the Python mathematical operators
available for you to use in your scripts.


TABLE 5.1 Python Math Operators

The floor division operator (//) returns the integer portion of a division result (what we use to call
the “goes into” part, back in long division classes). The modulus operator returns the remainder of the
division (what we use to call the “left over” part).


You’ll notice from the table that there are two types of AND and OR operators. There’s a subtle
difference between the binary and logical operators. The binary operators are used in what’s called
bitwise calculations. You use bitwise calculations to perform binary math using binary values.


If you’re using binary operators, you’ll probably want to also specify your values in binary notation.
To do that, just use the 0b symbol in front of the number, like this:


>>> a = 0b01100101
>>> b = 0b01010101
>>> c = a & b
>>> bin(c)
'0b1000101'
>>>

To display the value of the c variable in binary notation, you just use the bin() function.


The logical operators work with Boolean True and False logic values. These are most often used
in if-then comparisons (see Hour 6, “Controlling Your Program”). Here’s an example of how they
work:


Click here to view code image


>>> a = 101
>>>b = 85
>>> if ((a > 100) and (b < 100)): print("It worked!")
Free download pdf