Click here to view code image
>>> test10 * 5
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
test10 * 5
NameError: name 'test10' is not defined
>>>
Not only can you use variables within a calculation, you can also assign the result of a calculation to
a variable. Python automatically sets the variable to the data type required to hold the calculation
result:
>>> test1 = 2 + 5
>>> result = test1 * 5
>>> print(result)
35
>>>
The result variable contains the result of the calculation, which you can then display by using the
print() function. As you can see in the example, you can use both variables with numbers
anywhere in the calculations.
The ability to assign numbers and calculation results to variables is crucial to using math in Python
scripts. Listing 5.1 shows the script0501.py script, which performs a simple math calculation
and then displays the result.
LISTING 5.1 The script0501.py Script
#!/usr/bin/python
test1 = 2 + 5
result = test1 * 5
print(result)
When you run the script0501.py script, all you should see is the output from the print()
function:
$ python3 script0501.py
35
$
All the math calculations performed in the script are hidden from view!
Floating-Point Accuracy
As you’ve been playing around with your calculations, you may have seen some odd behavior with
some of the floating-point calculations. Here’s an example of what we mean:
>>> 5.2 * 9
46.800000000000004
>>>
The result of 5.2 multiplied by 9 should be 46.8, but the result displayed in IDLE has a stray value
added to the actual result.
This is caused by the way the underlying CPU handles floating-point arithmetic. Because the floating-