Reputation: 127
I have a possibly very easy question which I can't seem to figure out how. How to do something like this:
race = goblin #I change the race here
goblingrowth = 200
humangrowth = 300
orgegrowth = 400
print (race + "growth") #In this case, it will print the string "goblingrowth" in
python, but I want it to print the value of the variable (goblingrowth),
which is 200, and i have to do it this way.
Any help will be greatly appreciated, thanks
Upvotes: 0
Views: 64
Reputation: 37509
You could just store the values in a dictionary instead of as separate variables.
growths = {'goblin': 200, 'humans': 300, 'ogre': 400}
print growths[race]
Upvotes: 3
Reputation: 3891
One way you could do this is to access the locals()
dictionary which holds the local variables of your code and get the value of the variable from the string that you have. For example:
race = 'goblin' #I change the race here
goblingrowth = 200
humangrowth = 300
orgegrowth = 400
print(locals()[race + 'growth']) # this accesses the variable goblingrowth in the locals dictionary
Would output 200
. Hope this helps!
Upvotes: -1
Reputation: 24052
A better way to do this is to have a class to represent your different types of living entities. You can then create an instance for each race, setting the properties. You will then have convenient access to all of the properties of a given living. For example:
class Living(object):
def __init__(self, name, growth):
self.name = name
self.growth = growth
goblin = Living("goblin", 200)
human = Living("human", 300)
ogre = Living("ogre", 400)
for living in (goblin, human, ogre):
print(living.name + " growth is " + str(living.growth))
This outputs:
goblin growth is 200
human growth is 300
ogre growth is 400
Upvotes: 2
Reputation: 26578
Simply add in goblingrowth
to your print as I will show below. However, the way you are looking to do this, you will have to cast your variable to a string (since your goblingrowth
is an int), which isn't very ideal. You can do this:
print(race + " growth " + str(goblingrowth))
However, it would be more proper and strongly recommended to structure your output like this instead using string formatting:
print("{0} growth: {1}".format(race, goblingrowth))
What happened above, is that you are setting the arguments in to each of those positions in the string, so {0}
indicates the first argument you are providing to format and set at that position of the string, which is race
, then {1}
will indicate the second argument provided to format, which is goblingrowth
. You actually don't need to provide those numbers but I suggest you read the documentation provided below to get more acquainted.
Read about string formatting here. It will help greatly.
Upvotes: 0