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

(singke) #1
It worked!
>>> if ((a > 100) and (b > 100)): print("It worked!")
>>>

After you enter the if statement, IDLE produces a blank line, waiting for you to complete the
statement. Just press the Enter key to finish the statement. In these examples, we compared two
conditions using the logical and operator. When both conditions are True, Python runs the
print() statement. If either one is False, Python skips the print() statement.


Order of Operations


As you might expect, Python follows all the standard rules of mathematical calculations, including the
order of operations. In the following example, Python performs the multiplication first and then the
addition operation:


>>> 2 + 5 * 5
27
>>>

And just like in math, Python allows you to change the order of operations by using parentheses:


>>> (2 + 5) * 5
35
>>>

You can nest parentheses as deeply as you need to in your calculations. Just be careful to make sure
that you match up all the opening and closing parentheses in pairs. If you don’t, as in the following
example, Python will continue to wait for the missing parenthesis:


>>> ((2 + 5) * 5

When you press the Enter key, IDLE returns a blank line instead of displaying the result. It’s waiting
for you to close out the missing parenthesis. To close out the command, just supply the missing
parenthesis on the blank line:


)
35
>>>

IDLE completes the calculation and displays the result.


Using Variables in Math Calculations


Probably the most useful feature of using math in Python is the ability to use variables inside your
equations. The variables can contain values of any numeric data type in Python math calculation. The
following example shows that if you mix data types in your calculations, Python will stick with the
floating-point data type for the result:


>>> test1 = 5
>>> test1 * 2.0
10.0
>>>

Be careful to assign a value to a variable before using it in a calculation, or Python will complain, as
in this example:

Free download pdf