How do you use loops in Robot Framework?

Robot Framework provides excellent support for loops, allowing you to repeat actions efficiently. Here's a breakdown of how to use them.

1. FOR Loops :
* Basic FOR Loop: This iterates over a range of values.
***Test Cases***
Example Loop
    FOR    ${i}    IN RANGE    1    6
        Log    Value of i: ${i}
    END?

This loop will execute 5 times, with ${i} taking values from 1 to 5.

* Iterating over a List: You can loop through items in a list.

***Variables***
@{FRUITS}    apple    banana    orange

***Test Cases***
Fruit Loop
    FOR    ${fruit}    IN    @{FRUITS}
        Log    Fruit: ${fruit}
    END

This will print each fruit in the list.

* Iterating over a Dictionary:
Loop through keys or key-value pairs in a dictionary.

***Variables***
&{USER}    name=John    age=30    city=New York

***Test Cases***
User Data Loop
    FOR    ${key}    IN    &{USER}
        Log    Key: ${key}, Value: ${USER}[${key}]
    END

    FOR    ${key}    ${value}    IN    &{USER}  # Loop through key-value pairs
        Log    ${key}: ${value}
    END


* IN ZIP for Parallel Iteration:
If you need to iterate over multiple lists simultaneously, use IN ZIP.

***Variables***
@{NAMES}    John    Jane    Mike
@{AGES}     25      32      28

***Test Cases***
Parallel Loop
    FOR    ${name}    ${age}    IN ZIP    @{NAMES}    @{AGES}
        Log    Name: ${name}, Age: ${age}
    END

2. Controlling Loop Flow :
* Exit For Loop If: Use this to exit the loop based on a condition.
***Test Cases***
Conditional Exit
    FOR    ${i}    IN RANGE    1    10
        Exit For Loop If    ${i} > 5
        Log    Value: ${i}
    END?

The loop will stop when ${i} becomes greater than 5.

* Continue For Loop If:
Skips the current iteration if a condition is met.

***Test Cases***
Skip Iteration
    FOR    ${i}    IN RANGE    1    10
        Continue For Loop If    ${i} == 3
        Log    Value: ${i}
    END

This will skip the iteration where ${i} is 3.

3. Nesting Loops :

You can nest loops for more complex scenarios.

***Test Cases***
Nested Loops
    FOR    ${i}    IN RANGE    1    3
        Log    Outer loop: ${i}
        FOR    ${j}    IN RANGE    1    3
            Log    Inner loop: ${j}
        END
    END

4. WHILE Loops (Simulated) :

Robot Framework doesn't have a direct WHILE loop, but you can simulate it using FOR loops and Exit For Loop If.

***Test Cases***
Simulated While Loop
    ${condition}    Set Variable    True
    FOR    ${i}    IN RANGE    1    1000  # Large range to ensure loop runs
        Exit For Loop If    '${condition}'=='False'
        Log    Looping...
        ${condition}    Set Variable    False  # Example: Condition changes
    END