DontAsk_
DontAsk_

Reputation: 182

How can I get variable from a different file using user input?

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

Answers (2)

Yuval.R
Yuval.R

Reputation: 1291

There are a couple of ways to achieve what you need.

  1. Instead of saving the variables just as variables, save them as a dictionary, like this:

pokemonList.py:

pokemon = {"charmander": "fire",
           "squirtle": "water"}

main.py:

import pokemonList

pokemon = input("select a pokemon: ")
print(pokemonList.pokemon[pokemon])
  1. You can use the 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

Andrew
Andrew

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

Related Questions