Reputation: 182
I'm working on a fun project with my friend and we're trying to figure out how to get a specific variable from a file using user input.
Example:
In pokemonList.py file
charmander = "fire"
squirtle = "water"
In main.py file
import pokemonList
pokemon = input("select a pokemon: ")
print(pokemonList.pokemon)
When I try that the program thinks I'm trying to get a variable called "pokemon" from the file. Is there any way to do this?
Upvotes: 1
Views: 60
Reputation: 1291
There are a couple of ways to achieve what you need.
pokemonList.py:
pokemon = {"charmander": "fire",
"squirtle": "water"}
main.py:
import pokemonList
pokemon = input("select a pokemon: ")
print(pokemonList.pokemon[pokemon])
eval
function to get the values (very unsafe and not recommended):pokemonList.py:
charmander = "fire"
squirtle = "water"
main.py:
import pokemonList
pokemon = input("select a pokemon: ")
print(eval("pokemonList."+pokemon))
Upvotes: 0
Reputation: 1082
Assuming that names are unique, I think a dictionary is a sensible approach:
in pokemonList.py:
pokemon = {"charmander" : "fire",
"squirtle" : "water"}
in main.py:
import pokemonList
pokemon = input("select a pokemon: ")
print(pokemon, " ", pokemonList.pokemon[pokemon])
Upvotes: 2