0

I am doing a program that simulates population growth, but I am not competent enough to understand how to assign a variable to a newly generated person.

Here's my (very much incomplete) code so far:

from random import seed
from random import randint
seed()

m = "male"
f = "female"

class Person:
    def __init__(self, gender, age):
        if gender == 0:
            self.gender = m
        else:
            self.gender = f
        self.age = age

def person_Birth():
    x = Person(randint(0,1), 0)
    return x

new_Person = person_Birth() #here's the problem

Every time i want to "cause birth" to a new human, how can i store his/her information separately i.e. automatically assign a new variable to store his/her information without explicitly stating a new variable?

I'm sorry if this is confusing to you, I am not sure of the correct terms.

2
  • I don't see anything wrong with this code. What are your expected results? Commented Nov 7, 2015 at 21:31
  • how about creating a list, and appending new person to the list every time you create one? Then you can reference the person by list index rather than by a specific variable. Commented Nov 7, 2015 at 21:34

1 Answer 1

1

You need to store the references to the people in a container structure like a list or a dictionary:

people = []
for _ in range(20):
    people.append(person_Birth())

Now the people list would contain 20 instances of Person, which you can either iterate over, or access each one individually with people[0] to people[19].

Sign up to request clarification or add additional context in comments.

2 Comments

I totally mis-read the OP question. I don't understand where I came up with my solution. Your solution totally makes sense. +1.
Thought about something like this, but would have never discovered about it myself. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.