Ranger Ranger - 2 years ago 118
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

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

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

>>> x

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download