4

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?

1
  • There is only for-in-loops in Python, you may generate a lazy sequence of all possibilities of r Commented Jan 19, 2021 at 2:39

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your comment! I have another question. Is there any way to performs this task by using for-loop?
1

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

4 Comments

Great idea, but: the generator should yield the tuple (r, s) so that these can be treated as loop variables, i.e. the consuming code would be for r,s in gen(n, k). Also, the yield r, s should be before the increment and decrement of variables so that the first values mimic that of a for loop.
@mhawke You are absolutely right. I modified my code.
I'd still change it to for r, s in gen(n, k) but that's up to the consumer to decide,
@mhawke Right. Done!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.