[Python] How to stop this while loop after it has run through a full array

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have this code that runs a loop, and it functions almost exactly how I want, except that I cannot get it to stop. Below is the relevant code:

    while(True):
    try:
    # File to persist counter
    COUNTER_FILE = 'run_counter.txt'

    def get_next_element(arr):
    """Get next array element using persisted counter"""

    # Read existing counter or initialize
    if os.path.exists(COUNTER_FILE):
    with open(COUNTER_FILE, 'r') as f:
    counter = int(f.read().strip())
    else:
    counter = 0

    # Get current element
    element = arr[counter % len(arr)] # Use modulo for circular behavior

    # Update counter
    counter += 1
    with open(COUNTER_FILE, 'w') as f:
    f.write(str(counter))

    return element

    # Example usage across multiple runs
    city_array = ['1', '2', '3']
    city = get_next_element(city_array)
    print(f"Assigned value: {city}")

    <---- Some Code below that runs Selenium, works fine ---->


    I understand that this sequence repeats on a forever loop because of while(True). I'm not sure what to change that loop to. I've also tried the simple solution:

    print(f"Assigned value: {city}")
    break


    If I use the break in the above snippet, the counter will stop at the first element in this array:

    city_array = ['1', '2', '3']


    • What is happening: It runs the full city_array ['1', '2', '3'], or [0, 1, 2], then it runs it again, infinitely.


    • What I want to happen: It runs the full city_array ['1', '2', '3'], or [0, 1, 2] -- then I want it to stop once it has run through the full array.

    Continue reading...

Compartilhe esta Página