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

(singke) #1

point data type converts the numbers into a special format, the calculations are somewhat inaccurate.


You can’t get around this problem in your calculations, but you can use some Python tricks to help
make things more presentable when displaying the results.


Displaying Numbers


One way to solve the floating-point accuracy issue is to display only the pertinent part of the result.
You can use the print() function to reformat the numbers that it displays.


By default, the print() function displays the actual result that’s calculated by Python:


>>> result = 5.2 * 9
>>> print(result)
46.800000000000004
>>>

However, you can use some Python tricks to help out with formatting the output.


Despite what the output looks like, the print() function actually produces a string object for the
output (in this case, the string just happens to look like the number result). Since the output is a string
object, you can use the format() function on the output (see Hour 10, “Working with Strings”),
which allows you to define how Python displays the string object.


The format() function allows you to separate the variable from the output text in the string object
by using the {} placeholder symbol:


Click here to view code image


>>> print ("The result is {}".format(result))
The result is 46.800000000000004
>>>

That hasn’t helped yet, but now you can use the special features of the {} placeholder to help you
reformat the output.


You just define an output template in the {} placeholder, and Python will use it to format the number
output. For example, to restrict the output to two decimal places, you use the template {0:.2f} to
produce this output:


Click here to view code image


>>> print("The result is {0:.2f}".format(result))
The result is 46.80
>>>

Now this is much better! The first number in the template defines what position in the number to start
to display. The second number (the .2) defines the number of decimal places to include in the output.
The f in the template tells Python that the number is a floating-point format.


Operator Shortcuts


Python provides a few shortcuts for mathematical operations. If you’re performing an operation on a
variable and plan on storing the result in the same variable, you don’t have to use the long format:


>>> test = 0
>>> test = test + 5
>>> print(test)
5
>>>
Free download pdf