-3

I'm making a text based game in python and want to check how many trees are in the field that i'm in.

I'm running the latest Python (3.7.1) (Not using IDLE it is just named Python3.7.1.exe and it looks like CMD) I'm trying to use variables like this but it is saying that I can't compare strings to integers (but how do I turn strings into "variable text"?).

trees_A1 = random.randint(…)
trees_A2 = random.randint(…)
…
Field = A3
if "trees_"+Field > 0

I expected it to compare trees_A3 but just sees the string trees_A3.

veben
  • 19,637
  • 14
  • 60
  • 80

3 Answers3

0

Use a dictionary!

trees = dict()
trees["A1"] = random.randint(…)
trees["A2"] = random.randint(…)
…
Field = "A3"
if trees[Field] > 0:
    …
Christian König
  • 3,437
  • 16
  • 28
0

You can use globals():

if globals()["trees_"+Field] > 0:

Or use a dictionary.

Austin
  • 25,759
  • 4
  • 25
  • 48
0

You are looking for eval() operator

a = 5
eval("a")

this will result

5

so you can evaluate strings with eval(). However you should not do that. Since eval is like an evil operator. They will cause security issues in your program. You should use dictionaries for your purpose.

trees = {}
trees["A1"] = random.randint(…)

then you should call trees["A1"] this way you will be write more pythonic and more proper code.