Question

im trying to print the next item in the list by using this function I defined below :

List = [1,2,3,4,5]

def next():
    i=0
    if (i<4): 
        i= i + 1

    print (List[i])

The output of this remains as the second index and doesn't increments no matter how many times i call it

Thanks.

Was it helpful?

Solution

i in the next function is a local variable. It is always initialized to 0 when the function is called.

To make the variable i remember the last value, make it as a global variable.

i = 0 # <--- global variable

def next():
    global i # <--- declare `i` as a global variable
    if (i<4): 
        i= i + 1

    print (List[i])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top