mardi 25 septembre 2018

Independant Variable for Function when called Multiple Times

I'm trying to create a function that will print an element in a list. However, I want it so I can print the next element every time the function is utilized in an If Statement. Here's what I got:

import random

index = 0
list1 = ['one', 'two', 'three', 'four', 'five', ]
list2 = ['uno', 'dos', 'tres', 'cuatro', 'cinco', ]

def reshuffle(list):
    global index
    if index < len(list):
        print(list[index])
        index += 1
    elif index == len(list):
        random.shuffle(list)
        index = 0
        print(list[index])
        index += 1

while True:
    user_input = input("Enter command: ")
    if user_input == "e":
        print(reshuffle(list=list1))
    if user_input == "s":
        print(reshuffle(list=list2))

What happens is whenever the function prints off all the elements in the list with the if statement, it shuffles them and starts over. It does this by using index, but each time the function is used by more than one if statement, it reads off the same variable. The output looks like this:

Enter command: e
one
None
Enter command: e
two
None
Enter command: s
tres
None
Enter command: s
cuatro
None

I want it to do this:

Enter command: e
one
None
Enter command: e
two
None
Enter command: s
uno
None
Enter command: s
dos
None

How can I have each function call use the same variable independently, without resetting the variable? Or if there's another way to approach this, any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire