[Tutor] Newline

Steven D'Aprano steve at pearwood.info
Sat Dec 4 18:00:35 CET 2010


Alex Hall wrote:
> On 12/4/10, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> "Steven D'Aprano" <steve at pearwood.info> wrote
>>
>>>>>> for i in (1, 2, 3):
>>> ...     print(i, "spam", end="\n" if i==3 else "***")
>> Ooooh! A new trick.
>> I hadn't thought of using the conditional expression there but it
>> makes a lot of sense.
>> Definitely more fun and flexible than the old comma at the end of a
>> print in v2 :-)
> So is this a python3.x feature only? Is there an equivallent in 2.x? I
> had not realized if statements could be used in calling functions like
> that or that they could be arranged in that way, but I am sticking to
> python2 since most packages are still written for it.


Python has had "if" expressions (also known as the ternary operator) 
since Python2.5. You can write:

true_value if condition else false_value

anywhere that will accept an expression. E.g.:

len("chicken" if today == tuesday else "fish")

Since Python2.6, you can get the print function by using:

from __future__ import print_function

Note that there are TWO underscores at the start and end of 
"__future__", and that like all __future__ imports it must be the first 
executable line of your script or module.


-- 
Steven



More information about the Tutor mailing list