Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 699
nemesisdesign Avatar asked Dec 27 '22 18:12

nemesisdesign


1 Answers

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.

like image 82
Rostyslav Dzinko Avatar answered Dec 29 '22 09:12

Rostyslav Dzinko