Python equivalent of Ruby's expression: "puts x += value"

11,750

Solution 1

The reason why you can not do exactly or very similarly the same in Python is because in Ruby, everything is expression.

Python distincts between statements and expressions and only expressions can be evaluated (therefore printed, I mean passed to print operator/function).

So such code cannot be done in Python in that form you showed us. Everything you can do is to find some "similar" way to write down statement above as a Python expression but it will definitely not be that "Rubyous".

IMHO, in Python, impossibility of such behaviour (as described in this use case), nicely follows "explicit is better than implicit" Zen of Python rule.

Solution 2

a one-liner to produce the same result:

for x in xrange(4,42,2): print x

gives:

4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40

xrange is a built in function that returns an “xrange object”, which yields the next item without storing them all (like range does), this is very similar to OP's while loop.

Solution 3

With the remarks about assigment not being expressions in Python on the other answers kept, one can do this in Python:

from __future__ import print_function

[print(x) for x in range(0,42,2)]

Solution 4

This is not possible in python; you can't use a statement (x += 2) as an expression to be printed.

Share:
11,750
nemesisdesign
Author by

nemesisdesign

Here mainly to ask questions about Javascript, React, Python, Flask and Django, but sometimes also Ruby and Ruby on Rails and Lua. OpenWISP contrbutor.

Updated on June 18, 2022

Comments

  • nemesisdesign
    nemesisdesign almost 2 years

    For curiosity's sake...

    In Ruby:

    =>$ irb
    1.8.7 :001 > puts x = 2
    2
     => nil 
    1.8.7 :002 > puts x += 2 while x < 40
    4
    6
    8
    10
    12
    14
    16
    18
    20
    22
    24
    26
    28
    30
    32
    34
    36
    38
    40
    

    It's quite handy.

    Is it possible to do that in Python in a single line and if yes how?

  • nemesisdesign
    nemesisdesign over 11 years
    The first two pharagraphs of your answer explained it all. I'm not trying to find a "Rubyous" way to do something in Python, I just find comparing the two languages quite instructive. Is there a way to achieve the same loop in one line in python? I never use that kind of expressions in python, but as far as I know I can't do that in python, so I was wondering if it would be possible somehow.
  • nemesisdesign
    nemesisdesign over 11 years
    "for i in xrange(4,42,2): print i" also
  • zenpoy
    zenpoy over 11 years
    @nemesisdesign even better :)
  • Mark Thomas
    Mark Thomas over 11 years
    Not sure I understand your ZoP reference. What's implicit about the given code?