Dictionary help!

I am making a text based civlization sim and I ran into trouble. I was trying to pass the for loop for a set amt of time using a variable. however, it thought my variable was apart of my dictionary, and got confused:

import random as rd

generations = input("How many generations: ")

humanity = {
  "men": 1,
  "women": 1,
  "children": 2

for generations in humanity:
    if humanity["women"] > 0 and humanity["men"] > 0: 
        humanity["children"] = humanity["children"] + rd.randint(0, 2)
    men_adulting = humanity["children"] * rd.randint(0, 1)
    humanity["men"] = humanity["men"] + men_adulting
    humanity["children"] = humanity["children"] - men_adulting


Please don’t steal this by the way!!

1 Like

This means: create a new integer from the generations string, and then throw it away.

This means: each time through the loop, set generations to be one of the keys in the humanity dict. The previous value of generations (the string from the previous input, since the int result was thrown away) is overwritten.

So it will loop three times, because there are three key-value pairs in humanity (and this doesn’t change as the loop runs).

You want:

generations = int(generations)

and then

for _ in range(generations):

It doesn’t matter what “counter” variable name (between for and in) you use here (as long as it doesn’t replace something else you need). Calling it _ is a common way to signal that we don’t care about it and won’t use it (although we can). A for loop works by giving you each value from a collection, in turn. If you want to do something a specific number of times, generally we just make up a separate collection to use, and ignore what it actually contains. The built-in range is the easiest and most idiomatic way to do that.

Corresponding Stack Overflow Q&A:

1 Like

You probably want this:

# Input() always returns a string. So change it to an int.
generations = int(input("How many generations: "))

Your game will probably expand in complexity where each man, woman and child will have many attributes. Have you looked into using classes? Each man and woman could have these attributes:

  • health
  • age
  • isworking (boolean). If this is false then they are idle.
  • ctrclass: are they a worker, fighter, blacksmith, etc.
  • movespeed: how fast they move.

There are good, free tutorials on Youtube for all kinds of Python things. I like the Indently guy.