Am Mon, 17 Sep 2012 23:27:34 +0100
schrieb David W Noon <dwn...@ntlworld.com>:

> On Mon, 17 Sep 2012 17:17:47 -0400, Philip Webb wrote about Re:
> [gentoo-user] new machine : suddenly Python 3 appears:
> 
> > 120917 Philip Webb wrote:
> > > 120917 David W Noon wrote:
> > >>    print('              {0}'.format(eval(expression)))
> > 
> > That works properly with Python2 in this machine ;
> > I'll check it with Python3 later in the new machine.
> 
> That *is* Python 3 syntax.  It is also accepted under recent releases
> of Python 2.
> 
> > > 120917 Marc Joliet wrote:
> > >>   print('              ',eval(expression))
> > 
> > That does the calculation, but the output is wrongly formatted :
> > 
> >   514 bin> pycalc1 2+3
> >   ('              ', 5)
> 
> This is because Marc's code is syntactically invalid for Python 3.  It
> is acceptable to Python 2, but does not do what you want; but it won't
> work at all under Python 3.

No, he simply executed it using python2, hence he printed a tuple. My version
certainly prints the exact same output as the python2 version, *when executed
by python3*. You tried it out first, right? I certainly did.

Note that the only difference to your version is that yours does string
formatting via str.format(), which also exists in Python 2. That of course has
the advantage of working the same in Python 2 and 3 (*if* you care about that):
the argument to print is not a tuple anymore, so it is not formatted as such:

  $ python3 -c "print('{0}'.format(3))" 
  3
  $ python2 -c "print('{0}'.format(3))"
  3

> It is clear that you have not taken my advice to use the -3 run-time
> option in your hash-bang line.  At the risk of blowing my own trumpet,
> that was *extremely sound* advice; you should really take it.  It would
> have revealed the problems with the above code during the Python
> interpreter's initial scan of the code.  I'll repeat it:
>     !#/usr/bin/python2 -3
> This will perform a Python 3 syntax check, even under Python 2.  It
> will identify any going-forward issues for your Python script(s).

I also just remembered the "2to3" program, which will translate trivial (such
as print vs. print()) and (I think) some not so trivial cases to python3 syntax
for you. Personally I think you should just convert your scripts to python3 and
be done with it, unless you want to avoid python3 forever.

Of course, Philip did say this is his only python script, so using "python2 -3"
might actually be a tad overkill for his purposes, unless he wants to start
learning python, in which case: why not just start with python 3?

HTH
-- 
Marc Joliet
--
"People who think they know everything really annoy those of us who know we
don't" - Bjarne Stroustrup

Attachment: signature.asc
Description: PGP signature

Reply via email to