Variables scope in script

I guess i miss something but variable scope is not clear for me ,
In simple iteration i expect to print current # of cycle in the iteration,
actual - it printing always “1”

set_number_of_run:
  sequence:
    - variables:
        iterator: "{{ states('input_number.predefine_number') }}"
        curr_cycle: 0
    - condition: "{{ states('switch.hot_water') != 'on' }}"
    - repeat:
        count: "{{ iterator }}"
        sequence:
          - variables:
              curr_cycle: "{{ curr_cycle + 1 }}"            
          - if:
              - condition: state 
                entity_id: switch.hot_water
                state: "off"
            then:                 
              - delay: 5            
              - service: switch.turn_on
                data:
                  entity_id: switch.hot_water
              - delay: 5                              
              - service: notify.avi
                data:
                  title: Test loop based input number
                  message: "{{curr_cycle }}  out of {{ iterator | int }} "     
          - wait_template: "{{ is_state('switch.hot_water', 'off') }}"
          - delay: 5

I actually tried to place the

          - variables:
              curr_cycle: "{{ curr_cycle + 1 }}"   

also in the “then” section

My understanding is that it works similarly to python for loops where you cannot change the value of a variable outside the loop from within the loop. As such, there are some Built-in Repeat Variables that handle index and other loop aspects.

set_number_of_run:
  sequence:
    - variables:
        iterator: "{{ states('input_number.predefine_number') }}"
    - condition: "{{ states('switch.hot_water') != 'on' }}"
    - repeat:
        count: "{{ iterator }}"
        sequence:          
          - if:
              - condition: state 
                entity_id: switch.hot_water
                state: "off"
            then:                 
              - delay: 5            
              - service: switch.turn_on
                data:
                  entity_id: switch.hot_water
              - delay: 5                              
              - service: notify.avi
                data:
                  title: Test loop based input number
                  message: "{{ repeat.index }}  out of {{ iterator | int }} "     
          - wait_template: "{{ is_state('switch.hot_water', 'off') }}"
          - delay: 5
1 Like

Thanks , it does provide me the solution,
I started to think if such logic should be implemented as automation and not script,
would appreciate any advise .