简体   繁体   中英

How condition can be executed without breaking the loop in python

I tried to iterate over a list again and again but when the first round is finished I have to print dashes. But the dashes are printing before the round gets fully finished. Here is what I tried so far:

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    n = (n+1) % len(lit)
    if lit[n] == lit[-1]:
        print('-'*80)

I also tried the following condition too but it didn't work

if n == len(lit):
    print('-'*80)

here is what I'm getting

1
2
3
4
--------------------------------------------------------------------------------
5
1
.

here is an expected output

1
2
3
4
5
--------------------------------------------------------------------------------
1
.

The proper test would be n == 0 .

Update your n after the print:

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    if lit[n] == lit[-1]:
        print('-'*80)
    n = (n+1) % len(lit)

Output:

1
2
3
4
5
----------------

I am not sure if I got the question correctly. Isn't this enough?

from time import sleep as p

lit = [1, 2, 3, 4, 5]
while True:
    for n in lit:
        p(1)
        print(n)
    print('-'*80)

I think this should work for you,

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    n = (n+1) % len(lit)
    if lit[n-1] == lit[-1]:
        print('-'*80)

Make sure you do things in the correct order

First print the number
Then if the number is the last element, print the line
Finally increment the number

Your code but rearranged:

from time import sleep as p

lit = [1, 2, 3, 4, 5]
n = 0
while True:
    p(1)
    print(lit[n])
    if lit[n] == lit[-1]:
        print('-'*80)
    n = (n+1) % len(lit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM