Ranger Ranger - 7 months ago 14
Python Question

Python single line while loop

In Python, I am trying to make a variable increment in value while it is less than another number. I know that it is possible to do a

for
loop in the form
(print(x) for x in range(1, 5))
. My question is, is there a similar way to do a
while
loop in this form, such as
x += 1 while x < y
?

Answer
x = 0
y = 10
while x < y:
    x +=1

>>> x
10

Well you can do it in a single line because Python allows that:

x = 0
while x < y: x +=1

It is not as readable, and it doesn't conform to PEP 8, but it is doable.

Comments