Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple variables inside the Python for loop?

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?

like image 704
frankiie Avatar asked Nov 01 '25 18:11

frankiie


1 Answers

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
like image 161
Selcuk Avatar answered Nov 04 '25 10:11

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!