The Total


#1

Don't understand how did some people got this result, print ("%.2f" % total), please explain, thank you.


#2

This is string formatting for orderly output.

%        => space holder for value in parameter list
.2       => two decimal places
f        => float type expected

% total  => parameter list (arguments)

The parens are not needed in Python 2, but in Python 3, print is a function so they are needed. We're working in Python 2.


#3

would you be able to break it down?


#4

sorry , I see it now.


#5

from math import pi

print pi            # 3.14159265359

print "%.3f" % pi   # 3.142

Notice the difference?

Placeholders must be accompanied by an expected type symbol

%s   => string type
%d   => digit (integer type)
%f   => float type
%b   => boolean type
%r   => object representation

We've seen above that floats can be given a limit on decimal places. This works like round() using the 5/4 rule (up on 5, down on 4).

Note: A single argument in the parameter list does not need to be parenthesized, but multiple arguments must be written as a tuple (comma separated in parens).

To further explain... This is a form of string interpolation that permits us to write anything in the string we like, and interpolate the variables. The function converts all inputs to string for output, so the quotes are absolutely needed like they would for any string.

quantity = 5
price = 5.99
tax = 0.05
total = quantity * price * (1 + tax)

print "Quantity: %d @ %.2f plus tax @ %.2f for total: %.2f." \
% (quantity, price, tax, total)

Quantity: 5 @ 5.99 plus tax @ 0.05 for total 31.45.

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.