Reputation: 498
I'm a Java guy, currently learned Python. I'm stuck on how to use multiple conditions inside the Python for-loop.
here is the Java code
for (int r = n-1, s = k+1; r > s; r--, s++)
// some code
How can I convert this into Python for-loop?
Upvotes: 4
Views: 114
Reputation: 59445
This can best be implemented as a while
loop. It is more verbose than Java but also more Pythonic and, in my personal opinion, more readable:
r = n - 1
s = k + 1
while r > s:
# some code
r -= 1
s += 1
Update: You can use a for
loop but it's not as pretty:
p = (k + n) // 2
for r, s in zip(range(n - 1, p, -1), range(k + 1, p + 1)):
# some code
Upvotes: 5
Reputation: 5489
If you insist on doing it with a for loop, you can create a generator:
def gen(n, k):
r = n - 1
s = k + 1
while r > s:
yield (r, s)
r -= 1
s += 1
for x in gen(n, k):
#some code
#alternatively:
for x, y in gen(n, k):
#some code
Upvotes: 1