0

Why do i get the name is not defined error as shown below at the line "for character in SECRET_WORD:" even though earlier on in "def category" function that i have created, i defined SECRET_WORD to be SECRET_WORD = random.choice(word_list)?

  import random

    # Store the category and values into a dictionary
    categories = {
        "objects": ["tables", "ladders", "chairs"],
        "animals": ["chicken", "dog", "cat"],
        "sports": ["basketball", "soccer", "rugby"]

    }

    def category():
        print("Please enter category name: ")
        response = ''

        #Keep prompting the user to only enter allowed category values
        while response.lower() not in categories:
            # join(map(str, list((*categories,))) is used for retrieving the key values i.e. the category values from the dictionary "categories" and then join them as a string in order to display the allowed values back to the user
            response = input(' One among the following [%s] : \n' % ', '.join(map(str, list((*categories,)))))

        if response in categories:
            word_list = categories.get(response)
            # Print a random value from the chosen category
            print(random.choice(word_list)
            SECRET_WORD = random.choice(word_list)
            LENGTH_WORD = len(SECRET_WORD)
            GUESS_WORD = []
            ALPHABET = "abcdefghijklmnopqrstuvwxyz"
            letter_storage = []

    def prepare_secret_word() -> None:
        """Prepare secret word and inform user of it"""
        for character in SECRET_WORD: # <---------------- Name "SECRET_WORD" not defined error here"
            GUESS_WORD.append("-")
        print("Ok, so the word You need to guess has", LENGTH_WORD, "characters")
        print("Be aware that You can enter only 1 letter from a-z\n\n")
        print_word_to_guess(GUESS_WORD)

    # Call the function
    category()
    prepare_secret_word()

updated changes with my latest code (theres still error) shown below

  import random


category_lists = {
    "objects": ["tables", "ladders", "chairs"],
    "animals": ["chicken", "dog", "cat"],
    "sports": ["basketball", "soccer", "rugby"]

}

def category():
    print("Please enter category name: ")
    response = ''
    while response.lower() not in category_lists:
        # join(map(str, list((*categories,))) is used for retrieving the key values i.e. the category values from the dictionary "categories" and then join them as a string in order to display the allowed values back to the user
        response = input(' One among the following [%s] : \n' % ', '.join(map(str, list((*category_lists,)))))

    if response in category_lists:
        word_list = category_lists.get(response)
        # do what ever you want with the list
        SECRET_WORD = random.choice(word_list)
        LENGTH_WORD = len(SECRET_WORD)
        return SECRET_WORD
        return LENGTH_WORD


GUESS_WORD = []
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []




def prepare_secret_word() -> None:
    """Prepare secret word and inform user of it"""
    SECRET_WORD = category()
    LENGTH_WORD = category()
    for character in SECRET_WORD: # printing blanks for each letter in secret word
        GUESS_WORD.append("-")
    print("Ok, so the word You need to guess has", LENGTH_WORD, "characters")
    print("Be aware that You can enter only 1 letter from a-z\n\n")


category()
prepare_secret_word()
cena
  • 410
  • 1
  • 4
  • 12
  • 2
    Each `SECRET_WORD` is local to it's function. Either you need to pass in `SECRET_WORD` as a parameter or make it a global variable. – Loocid Feb 28 '20 at 07:55
  • If you want to do that (which is not a good idea in your case), use global variables: https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – Joan Lara Feb 28 '20 at 07:55
  • @cena you can `return SECRET_WORD` from function and create variable ` SECRET_WORD = def category()` – Zaraki Kenpachi Feb 28 '20 at 07:57
  • Hey cena, it's probably a good idea to read up on variable scope. As Loocid mentioned, when you used `SECRET_WORD` in the `category()` function, there was no previous mention, so it became a local variable, that cannot be referenced outside that function. – João Amaro Feb 28 '20 at 07:57
  • @Loocid how do you pass it as a parameter or global? – cena Feb 28 '20 at 08:06
  • @Zaraki kenpachi ah i see so i supposed i have to write return SECRET_WORD at the end of my def category(): function? – cena Feb 28 '20 at 08:07
  • @Loocid to pass it on as a parameter, is it something like def prepare_secret_word(SECRET_WORD) ? – cena Feb 28 '20 at 08:11
  • however i get the "prepare_secret_word() missing 1 required positional argument: 'SECRET_WORD' error" when i try to do that – cena Feb 28 '20 at 08:14

1 Answers1

1

You can make this:

def category():
    if response in categories:
        SECRET_WORD = random.choice(word_list)
    else:  # define else result
        SECRET_WORD = ''
    return SECRET_WORD


def prepare_secret_word():
    # get variable from function
    SECRET_WORD = category()
    for character in SECRET_WORD:
        #####  

# run
prepare_secret_word()
Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38
  • is it possible for a function to return two variables? Because my "LENGTH_WORD = len(SECRET_WORD)" is also consider not defined as well and i tried put return SECRET_WORD,LENGTH_WORD but it doesn't work that way – cena Feb 28 '20 at 08:23
  • i have just updated my codes to let you see the changes i have made based on your suggestions.. – cena Feb 28 '20 at 08:26
  • @cena for 2 variables just do: `return SECRET_WORD, LENGTH_WORD` and then: `SECRET_WORD, LENGTH_WORD = category()` – Zaraki Kenpachi Feb 28 '20 at 08:34
  • i have updated my code again based on your suggestions. This time round there is no error but by doing this, this will prompt the user to input category name three times. Why is this so? Is there a way to prevent it? – cena Feb 28 '20 at 08:54
  • @cena don't run `category()` at the end, replace `SECRET_WORD = category() LENGTH_WORD = category()` with `SECRET_WORD, LENGTH_WORD = category()` – Zaraki Kenpachi Feb 28 '20 at 09:40