pythonloopsdictionary

Python iterate every 10 items on button press


I'm struggling trying to iterate every 10 items

So if the list is bellow 10 items it goes perfectly well of curse

If the list is bigger then for every y pressed I want to show the next 10 items like a next page button and also not blowing at the end if I try to get the last 10 items and there's only 5 left

typing y to do next page and any other key previous page

Also note that this is not the real problem. The real one I'm facing is within curses module but I tried to simplify and even that I can't

display = 0
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

while True:
    # tried this but I need button press
    
    # for i in range(0, len(list), 10):
    #     print(*list[i:i+10])
        

    if len(list) <= 10:
        for i in list:
            print(i)
    else:
        for i in range((display * 10), ((display * 10) + 10) ):
            print(list[i])
            
    np = input()
    if np == 'y':
        display += 1
        # here something that would prevent the next page when there is no more items
    else:
        if display == 0:
            display = 0
        else:
            display -= 1

Solution

  • I'm sure there are many ways to solve this. One way is iterate over the data printing out the number of entries for the page size (e.g. 10) and then wait for user key press. Then only exit the loop once the data is exhausted.

    I've created the following example which generates data of random length for testing purposes:

    import random
    start = 1
    # Generate content of fixed length for testing
    # length = 20
    # Generate content of variable length for testing
    length = random.randint(5, 40)
    data = range(start, start + length)
    
    print(f"Created data {len(data)} long\n")
    
    PAGE_SIZE = 10
    
    def pages_needed(data_len):
        max_page = data_len // PAGE_SIZE
        if data_len % PAGE_SIZE > 0:
            max_page += 1
        return max_page
    
    
    page_number = 0
    data_available = len(data) > 0
    
    
    while data_available:
        page_start = page_number * PAGE_SIZE
        page_end = min((page_number * PAGE_SIZE) + PAGE_SIZE, len(data))
        total_pages = pages_needed(len(data))
        for entry in data[page_start:page_end]:
            print(f"\t{entry}")
        page_number += 1
        if page_number >= total_pages:
            data_available = False
        else:
            input("Press <return> for the next page of data")
    
    

    Which gave me the following output:

    Created data 17 long
    
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
    Press <return> for the next page of data
        11
        12
        13
        14
        15
        16
        17