Monday, 25 March 2019

How to rewrite this simple loop using assignment expressions introduced in Python 3.8 alpha?

It appears to me that it is not that straight forward to interchange classic while loops with assignment-expressions-loops keeping the code looking great.

Consider example1:

>>> a = 0
>>> while (a := a+1) < 10:
...     print(a)
... 
1
2
3
4
5
6
7
8
9

and example2:

>>> a = 0
>>> while a < 10:
...     print(a)
...     a += 1
... 
0
1
2
3
4
5
6
7
8
9

How would you modify example1 in order to have the same output (not skipping the 0) of example2? (without changing a = 0, of course)



from How to rewrite this simple loop using assignment expressions introduced in Python 3.8 alpha?

No comments:

Post a Comment