Reputation: 5
full code is here: https://repl.it/repls/UnevenLovingDecagons
line 29 with colony_size=(randrange(50,150)) is outside of loop
then at line 42 loop starts. colony_size is in line 45 as well. I would like the colony_size to be influenced by line 29 only once. With second run of loop I'd like the colony_size to be influenced only by what is going on inside of the loop. How can I do so?
part code below:
colony_size=(randrange(50,150))
the one above is still outside of loop colony_size=(colony_size+immigrants)-died this one is inside enter code here enter code here enter code here
Upvotes: 1
Views: 57
Reputation: 1238
The concept you're looking at is scope. Loops do not have their own scope in python, the why of this was asked in this question: Scoping in Python 'for' loops
After the following code is executed:
x = 1
i = 1
for i in (2,3,4,5):
x = i
both x and i will contain 5. And the same would be true if they were set or changed in any other kind of loop.
There are several ways to control the scope.. and the most common is functions, which you aren't using in your code. Their variables are contained in their own scope, and you must explicitly pass variables to and from them (using the return keyword). You could also consider comprehensions, although their variables were not contained in the same way in earlier versions of python.
More specifically, in your code.. you may consider putting everything in the while True
loop into a function.. (my_function as an example)
while True:
my_function(colony_size)
Or something like that. Then it will use the original colony_size the next time it runs (since you did not return it)
Of course, perhaps the easier option here is to just use a different variable name.
Upvotes: 1
Reputation: 11
You should have another variable to define a default colony_size
at line 29 like:
default_colony_size = (randrange(50,150))
Then define colony_size
as a an empty int or just 0
before the loop.
At the start the loop you want to want to do something like this:
if colony_size == 0 colony_size = default_colony_size
Pardon syntax errors as I do not know Python very well
Upvotes: 0