SkyWalker
SkyWalker

Reputation: 38

Using variables from other files calling it by using variables

This is my code for file_1:

type_Of_word = [
    'movies',
    'animals',
    'characters'
]

movies = [
    'Thor',
    'Tangled',
    'Forzen',
    'Spider-Man: No Way Home'
]

animals = [
    'Zebra',
    'Porcupine'
]

characters = [
    'Mickey Mouse',
    'Loki Odinson'
]

And my code for file_2:

import random
import gile_1

word = None

def get_word():
    type_of_word_choice = random.choice(file_1.type_Of_word)
    global word
    word = random.choice(file_1.type_Of_word_choice)
    print(word)

What I want to do is to use the name of the type stored in 'type_of_word_choice' and call the specific variable with the list of names and get the random choice of word.

But when I run this, it tells me:

Traceback (most recent call last):
  File "c:\Users\aisha\.codeVS\hangman\firstHangman.py", line 95, in <module>
    get_word()
  File "c:\Users\aisha\.codeVS\hangman\firstHangman.py", line 9, in get_word
    word = random.choice(words.type_Of_word_choice)
AttributeError: module 'words' has no attribute 'type_Of_word_choice'

Do you know how to solve this?

Upvotes: 0

Views: 57

Answers (2)

kindall
kindall

Reputation: 184465

Define your words as a nested dictionary structure.

words = {
    'movies': [
        'Thor',
        'Tangled',
        'Frozen',
        'Spider-Man: No Way Home'
    ],
    'animals': [
        'Zebra',
        'Porcupine'
    ],
    'characters': [
        'Mickey Mouse',
        'Loki Odinson'
    ]
}

Then write your code to first choose a random category, then a word from that category.

def get_word():
    type_of_word = random.choice(list(words))
    word = random.choice(words[type_of_word])
    return word

print(get_word())

Upvotes: 1

Corralien
Corralien

Reputation: 120559

Use getattr to dynamically get your second list (movies, animals or characters).

import random
import words

def get_word():
    type_of_word_choice = random.choice(words.type_Of_word)
    word = random.choice(getattr(words, type_of_word_choice))
    return word

word = get_word()
print(word)

# Output sample
Mickey Mouse

Note: don't use global variables. If you call a function return a value to set your variable.

Upvotes: 1

Related Questions