0

I am learning python and was trying my first dummy project. I wrote a function, in which a user can continue the code execution if s/he types one of the values from the list, or stop the code, if s/he types the other value from another list. Here is the function

myList=['','','','','','','','','',]
def continueGame():
    options  = True
    optionList1=['Yes', 'Y','y','yes','YES']
    optionList2=['No','no','n','NO']
    userChoice = ''
    while userChoice not in optionList1 and userChoice not in optionList2:
        userChoice = input("Want to continue the game ? (Y,N) :")
        if(userChoice not in optionList1 and userChoice not in optionList2):
            print("This is not the correct option. Please enter either Y or N.")
            userChoice = ''
            
    if(userChoice in optionList1):
        #myList=['','','','','','','','','',] ---------->Code 1
        options =  True
    else:
        options =  False
        
    if options ==  True:                         -------> Code 2
        myList=['','','','','','','','','',]      -------> Code 2
    return options      

myList is a list defined as a global List, whose values change in other functions, not described here . I have tried two methods. Code 1 and Code 2 (in the code above). But none of them work. Even if the user hits Y or Yes, it does not execute either Code 1 or Code 2.

Can someone tell me where I am going wrong?

Asish
  • 760
  • 1
  • 10
  • 16
  • 2
    Seems like you are missing the global keyword. Check this link: https://www.geeksforgeeks.org/global-keyword-in-python/ It has a good explanation. – Afridi Kayal Aug 22 '21 at 04:21

1 Answers1

1

The variable myList inside the continueGame() function is only the same as the myList variable at the top if you specify that it should be. In particular, you should insert global myList like this:

def continueGame():
    global myList
<then the rest of your code>

That tells python that the myList variable inside the function isn't a new one, it's the one in the global scope.

Also, no need for that trailing comma in your lists.

maldata
  • 385
  • 1
  • 14