Reputation: 101
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
?
Upvotes: 2
Views: 6334
Reputation: 4940
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.
Upvotes: 2
Reputation: 2330
You could do something like this
n = 0
while n < 1000: rn += n if not (n % 3 and n % 5) else 0
What you are seeing is a conditional expression but it comes at the price of some reduced readability
Upvotes: 0
Reputation: 121
You can separate each statement with a semi-colon like so...
x = 0; y = 5
while(x < y): print(x); x=x+1
Upvotes: 0