Home > Software design >  How to continue for loop while exiting and returning to it
How to continue for loop while exiting and returning to it

Time:12-10

In python i am trying to run a script that will run through a for loop process the data and then come back to the next entry, However I cannot get my head around it. Attached is a very simple version of what i am trying to do

list = None


def main():
    global list
    list = [1,2,3,4,5,6,7,8,9,0]
    number = for_loop()
    printing(number)


def for_loop():
    for i in list:
        return(i)


def printing(number):
    print(number)

main()

in this case, i want it to print 1 to 0. Another point is the list length needs to be dynamic I know here it is static

CodePudding user response:

My apologies if I oversimplified your problem statement, but Python makes looping through a list and processing the elements of that list relatively straightforward. There are many approaches to it, but here is a simple example where "processing" means "printing":

def process_list(a_list):
    for an_element in a_list:
        # processing step goes here
        print(an_element)  # print for example

process_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])

Output:

1
2
3
4
5
6
7
8
9
0

CodePudding user response:

I think you're trying to implement a generator.

def gen():
    for e in [1,2,3,4,5,6,7,8,9,0]:
        yield e

def main():
    for x in gen():
        print(x)

main()
  • Related