It's great to have you chime in, Steven. I do wish you would stop pulling your punches, however. ;)
On Fri, Oct 22, 2010 at 17:23, Steven D'Aprano <st...@pearwood.info> wrote: > On Sat, 23 Oct 2010 12:42:50 am Richard D. Moores wrote: > >> So I wrote a function: >> >> def float2n_decimals(floatt, n): >> """ >> Given a float (floatt), return floatt to n decimal places. >> >> E.g., with n = 2, 81.34567 -> 81.35 >> """ >> return ("%%.%sf" % n) % floatt >> >> which works fine, > > > float2n_decimals(x, 3) > > is better written in place as: > > "%.*f" % (3, x) > > There's no need for a function for something so simple. Yes, but I needed one for ("%%.%sf" % n) % floatt . >> but a question remains: n is an integer. Why the >> 's' in '%sf'? > > Your function might be more clear if you split the formatting into two > lines: > > template = "%%.%sf" % n > return template % floatt > > The first line builds a template string from n. Now it becomes clear > what %s is for: it's to insert the n as a string into the template. %d > would express the intention of the function better. > OK, I'll do that. > > By the way, the function docstring is seriously misleading. It describes > a completely different function: > >> Given a float (floatt), return floatt to n decimal places. >> >> E.g., with n = 2, 81.34567 -> 81.35 > > It does nothing of the sort! What you are describing is the built-in > function round: > >>>> print round(81.34567, 2) > 81.35 > > What your function does is return a string, not a float. OK, point well-taken. > Besides, given > a float, where does n come from? A global variable? Yes. See line 5 of <http://tutoree7.pastebin.com/M2wnPzLr>. This version incorporates all your suggestions. > There is a convention for giving examples that you should follow. > Putting the three of these together, your docstring should say > something like: > > Given a float floatt and an integer n, returns floatt formatted > as a string to n decimal places. > > >>> float2n_decimals(2, 81.34567) > '81.35' I've never seen that convention, but I'll try to follow it. > > (BTW, I really hate the name "floatt". It makes me think you're > stuttering.) I'll use "x" instead. Anything you'd like to say about the rest of the script? Thanks, Steven. Dick _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor