Setting new variables in a while loop with calculations PYTHON -
i'm running population model, , wrong numbers come out because i'm setting variables new values, when want use old variables, loop automatically updates , uses new ones.
juvenile_population = 10 adult_population = 10 senile_population = 1 juvenile_survival = 1 adult_survival = 1 senile_survival = 0 birth_rate = 2 generations = 5 counter = 0 while counter < generations: juvenile_population = adult_population * birth_rate adult_population = juvenile_population * juvenile_survival senile_population = (adult_population * adult_survival) (senile_population * senile_survival) total_population = juvenile_population + adult_population + senile_population print("juvenile: ",juvenile_population) print("adult: ",adult_population) print("senile: ",senile_population) print("total: ",total_population) counter += 1
a friend said set new named variables, after 1 loop, won't same problem again? want variables update, after they've been printed, if makes sense. suggestions?
per @selcuk, use variable unpacking directly, nicer formatting looks unwieldly:
juvenile_population, adult_population, senile_population, total_population = (adult_population * birth_rate, juvenile_population * juvenile_survival, (adult_population * adult_survival) (senile_population * senile_survival), juvenile_population + adult_population + senile_population)
my suggestion either write helper function, , keep "like" values in dictionary so:
populations = {'juvenile': 10, 'adult': 10, 'senile': 1 } survivals = {'juvenile': 1, 'adult': 1, 'senile': 0} birth_rate = 2 generations = 5 def update_population(pops): juvie = pops['adult'] * birth_rate adults = pops['juvenile'] * survivals['juvenile'] seniles = pops['adult'] * survivals['adult'] + (pops['senile'] * survivals['senile']) return {k:v k,v in zip(['juvenile','adult','senile'],[juvie,adults,seniles])} counter = 0 while counter < generations: populations = update_population(populations.copy()) total_population = sum(populations.values()) print("juvenile: ",populations['juvenile']) print("adult: ",populations['adult']) print("senile: ",populations['senile']) print("total: ",total_population) counter += 1
Comments
Post a Comment