Template sensor, jinja help?

Hi Everyone!!
I’m trying to make a sensor that sums other sensor value. i try this but i cant achive my purpose, anyone can help me please?

      value_template: >
                  {% set sum = 0 %}
                  {% for state in [states.sensor.total_consumption] %}
                      {%- if  as_timestamp(now()) - as_timestamp(state.last_changed) < 100 -%}
                          {% set sum = sum + state.state|float %}
                      {%- endif %}
                  {%- endfor -%}

Your problem in case you haven’t worked it out since you posted, is that the scope of your changes to “sum” are only within each iteration of the for loop. Each loop starts again with sum = 0. The way to do this is to use namespaces. However I can’t get those to work properly, see my post about that.