简体   繁体   中英

Not able to break out of while loop

I have the following code:

with open('data.csv') as csvfile:
    data = csv.reader(csvfile, delimiter=' ')
    row_count = sum(1 for row in data)
    counter = 0
    while counter < row_count:
        for i in range(20):
            print('hello')
        counter = counter +1
        print('sleeping')
        time.sleep(10)

The data.csv file have over 100 lines. But I want my counter to print only 20 lines of hello and then sleep for 10 seconds and restart the operation again until it matches the number in row_count .

The output is fine in that it prints hello 20 times and prints sleep with a delay but this loop does not end when it reaches row_count which is 100. This keeps on running. What can I do for this loop to end after it reaches 100?

Your identation is incorrect. If you ident the line where you increment the counter it will do what you want. Currently you are doing 100 (or whatever row_number equals) lots of 20.

EDIT: I wrote this thinking that you wanted to print "Hello" row_number times, but reading your post back it seems that you actually want to print "Hello" row_number * 20 times, in which case surely 2000 is the correct answer?

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