Mike Cuddy Mike Cuddy - 1 year ago 61
Python Question

issue with count variable in Python while loop

I have an array of values:

increase_pop = [500, -300, 200, 100]

I am trying to find the index of the lowest and highest values. Most of my code works and everything seems to be going well except for one problem. The rest of my code looks like the following:

max_value = increase_pop[0]
min_value = increase_pop[0]

count = 0
while count < len(increase_pop):
if increase_pop[count] > max_value:
max_year = count
max_value = increase_pop[count]
elif increase_pop[count] < min_value:
min_value = increase_pop[count]
count += 1


This code gets me the values of the min and max exactly what I want. However, I also want the index values of those positions. So for the max value I have the variable max_year = count assigned to it. Thus, I would think that max_year would be assigned to the count at the position where max_value was found. However, when I do a print(max_year) I get the following error:

UnboundLocalError: local variable 'max_year' referenced before assignment

Does anyone know what my (probably) small/minor issue is? What am I forgetting?

Answer Source

You can make your codes more pythonic by using the feature of list:

min_value = min(increase_pop)
max_value = max(increase_pop)
min_value_index = increase_pop.index(min_value)
max_value_index = increase_pop.index(max_value)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download