[Tutor] syntax error

Nym City nymcity at yahoo.com
Fri Sep 18 01:17:50 CEST 2015


-Perfect. Thank you. 


     On Tuesday, September 15, 2015 5:00 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
   
 

 On 15/09/15 02:41, Nym City via Tutor wrote:
> Hello,
> I am also just trying to understand this code and could not understand the print statement.I would have just used:
>  print('cost:$',gross_cost)
> Do you mind telling little bit about what:
> print('cost: ${:.2f}'.format(gross_cost))
> does do and why one would use this over my plain version?

When in doubt use the >>> prompt:

 >>> gross_cost = 4.6
 >>> print('cost: $',gross_cost)
cost: $4.6
 >>> print('cost: ${:.2f}'.format(gross_cost))
cost: $4.60

So the .2f forces the output to be formatted as a floating
point number with 2 digits after the decimal point.
And the format() inserts the values into the {} markers
in the string to which its attached. Another longer example:

 >>> quantity = 4
 >>> unit_cost = 4
 >>> tax = 0.1
 >>> print('''I bought {} items at ${:.2f} with {}% tax,
... making a total cost of: ${:.2f}
... '''.format(quantity,
...          unit_cost,
...          int(tax*100),
...          quantity * unit_cost * (1+tax)))
I bought 4 items at $4.00 with 10% tax
making a total cost of: $17.60

Notice this time that :.2f forced the integer unit_cost(4)
to be shown as a float with 2 decimal places(4.00).

There are lots of other codes you can use to modify the
formatting.

Check the language reference in the docs under 'formatting':

https://docs.python.org/3/library/string.html#formatstrings

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


 
  


More information about the Tutor mailing list