How to use for loops in Robot Framework?

Understand what For Loops are in Robot Framework and how to use them to build efficient test cases. Run your Robot Framework tests on real devices and browsers using BrowserStack for better reliability.

Get Started free
How to use for loops in Robot Framework
Home Guide How to use for loops in Robot Framework?

How to use for loops in Robot Framework?

Robot Framework is an open-source automation framework used for test automation and RPA (Robotic Process Automation). For Loops in Robot Framework allow you to iterate over lists, dictionaries, or ranges, and execute a set of keywords multiple times. This is especially useful when working with large datasets, repeating test steps, or validating multiple inputs and outputs.

This guide explains how for loops work in Robot Framework, with practical examples, syntax breakdowns, and best practices to help you write cleaner and more efficient automated tests.

What is the Robot Framework?

Robot Framework is an open-source automation framework designed for test automation and robotic process automation (RPA).

It uses a simple, keyword-driven syntax that makes creating and managing test cases easy, even for users with minimal programming knowledge. It’s widely used for user acceptance testing, UI testing, and integration testing across different platforms and technologies.

What is the Purpose of For loops in Robot Framework?

The for loop Robot framework is to automate repetitive tasks, reduce manual effort, and make test scripts more efficient and maintainable.

For loops in Robot Framework can be used in various scenarios, such as iterating over a list of test data values to run the same test case with different input parameters or iterating over a set of UI elements to perform the same action on each element.

Key factors for using For loop in Robot Framework:-

  • For loops are used to iterate over a sequence of values or items in Robot Framework.
  • For loops can be nested, allowing multiple levels of iteration.
  • For loops are commonly used in Robot Framework to automate repetitive tasks, such as iterating over a list of test data or UI elements.
  • By using For loops, test scripts can be made more efficient, maintainable, and less prone to errors.
  • For loops can also be used with conditional statements, allowing for more complex control flow in test scripts.
  • For loops can also be used with user-defined keywords to perform a sequence of actions for each item.
  • The Continue For Loop If and Exit For Loop If keywords can be used to control the flow of a for loop based on a condition.
  • For loops can be used to iterate over a sequence of files or directories, allowing for file operations or data processing.
  • The ELSE statement can be used in a for loop to execute actions if the loop completes without interruption.
  • Loops can generate and verify test data or create dynamic test cases based on input parameters.

How to write a for loop in Robot Framework?

A FOR loop in Robot Framework is a control structure that allows us to repeat a set of actions a certain number of times, or to iterate over a list or range of values.

The basic syntax of a robot framework for loop example is as follows:

*** Variables ***
@{list} item1 item2 item3

*** Test Cases ***
Example Test
FOR ${item} IN @{list}
Log ${item}
# Perform other actions on ${item}
END
  • In this example, the FOR loop statement is used to iterate over the @{list} variable.
  • Within the loop, the ${item} variable is set to each item in the list and printed using the Log keyword.
  • Replace the “log” keyword with any other keyword to perform different actions on each item in the list.

You can also use Python’s built-in range function to iterate a specific number of times. Here is an example:

*** Test Cases ***
Example Test
FOR ${i} IN RANGE 5
Log ${i}
END
  • In this example, the FOR loop statement is used with the RANGE keyword to iterate five times, and the ${i} variable is set to the index of each iteration.
  • The Log keyword is used to print the index of each iteration.
  • You can replace the Log keyword with any other keyword to perform different actions within the loop.

Basic Syntax of For Loops in the Robot Framework

Robot framework for loop is used to repeat a set of steps a certain number of times or for a specific range of values.

The basic syntax for a for loop robot framework is as follows:

FOR ${index} IN RANGE ${start} ${end} [${step}]
[Keyword or Steps]
[Keyword or Steps]
[Keyword or Steps]
  • ${index}: A user-defined variable to store the current value of the loop iteration.
  • IN RANGE: A keyword used to specify the range of values for the loop.
  • ${start}: The starting value of the range.
  • ${end}: The ending value of the range.
  • ${step} (optional): The increment between each loop iteration. The default is 1.
  • Data-driven testing: For loops can be used to iterate through a set of test data and execute the same test steps with different data sets.

For example, if we have a list of usernames and passwords to test login functionality, we can use a for loop to iterate through the list and execute the login test with each set of credentials.

FOR ${user} ${password} IN ZIP @{usernames} @{passwords}
Input Text ${username_field} ${user}
Input Text ${password_field} ${password}
Click Button ${login_button}
Wait Until Page Contains ${welcome_message}
Click Button ${logout_button}
  • Processing lists or tables: It can process a list or table of data and perform the same actions on each item in the list or table.

For example, if we have a list of products and their prices, we can use a for loop to calculate the total cost of all the products.

FOR ${product} ${price} IN ZIP @{products} @{prices}
${subtotal} = Evaluate ${price} * ${quantity}
${total} += ${subtotal}
  • Generating test data: It can be used to generate test data and execute test cases with the generated data.

For example, if a test case requires a unique email address each time it is executed, we can use a for loop to generate a list of unique email addresses and execute the test case with each email address.

FOR ${i} IN RANGE 1 ${number_of_tests}
${email} = Generate Unique Email
Run Keyword And Continue On Failure Submit Registration Form ${email} ${password}
  • Repeating actions a fixed number of times: It can be used to repeat a set of actions a fixed number of times. For example, if we need to execute a set of test steps 10 times to test stability and performance, we can use a for loop to repeat the set of steps 10 times.
FOR ${i} IN RANGE 1 10
Click Button ${random_button}
Wait Until Page Contains Element ${random_element}
Click Button ${back_button}

These are just a few examples of the many ways for loops can be used in Robot Framework for real-time use cases. The versatility of the for loop syntax allows us to apply them in a wide range of testing scenarios.

Using For Loops with Lists in the Robot Framework

In the Robot Framework, you can use For Loops with lists using the built-in FOR loop construct in combination with Python code. Here’s an example of how to do this:

Define your list in a test case or keyword: 

*** Test Cases ***
Example Test Case
${my_list}= Create List item1 item2 item3
FOR ${item} IN @{my_list}
Log ${item}
END

In the above example, the Create List keyword creates a list with items item1, item2, and item3. The FOR loop then iterates through each item in the list and logs the item to the console.

You can also use Python code within the FOR loop to manipulate the list items:

*** Test Cases ***
Example Test Case
${my_list}= Create List item1 item2 item3
FOR ${item} IN @{my_list}
Log ${item}
END
  • In the above example, the Create List keyword creates a list with three items: 1, 2, and 3.
  • The FOR loop then iterates through each item in the list using the RANGE keyword, which generates a range of values from 0 to the length of the list.
  • The Python code within the loop multiplies each item by 2, effectively doubling its value. Finally, the Log List keyword logs the modified list to the console.

Note that the ${} syntax is used to access variables in Robot Framework. In the Python code within the FOR loop, the ${index} variable is used to access the current index of the list, and the ${my_list[${index}]} syntax is used to access the value of the list item at the current index.

Using For Loops with Dictionaries in Robot Framework

With Robot Framework, you can use the built-in FOR loop construct in combination with Python code for loops with dictionaries. Here’s an example of how to do this:

Define your dictionary in a test case or keyword:

*** Test Cases ***
Example Test Case
${my_dict}= Create Dictionary key1=value1 key2=value2 key3=value3
FOR ${key} IN @{my_dict.keys()}
${value}= Set Variable ${my_dict[${key}]}
Log Key: ${key} Value: ${value}
END
  • In the above example, the Create Dictionary keyword creates a dictionary with three key-value pairs.
  • The FOR loop then iterates through each key in the dictionary using the keys() method and sets the corresponding value to a variable using the ${my_dict[${key}]} syntax.
  • The Log keyword then logs both the key and value to the console.

You can also use Python code within the FOR loop to manipulate the dictionary items:

*** Test Cases ***
Example Test Case
${my_dict}= Create Dictionary key1=1 key2=2 key3=3
FOR ${key} IN @{my_dict.keys()}
${my_dict[${key}]}= Set Variable ${my_dict[${key}]} * 2
END
Log Dictionary ${my_dict}
  • In the above example, the Create Dictionary keyword creates a dictionary with three key-value pairs.
  • The FOR loop then iterates through each key in the dictionary using the keys() method.
  • The Python code within the loop multiplies each value by 2, effectively doubling its value.
  • Finally, the Log Dictionary keyword logs the modified dictionary to the console.

Note that the ${} syntax is used to access variables in Robot Framework. In the Python code within the FOR loop, the ${key} variable is used to access the current key of the dictionary, and the ${my_dict[${key}]} syntax is used to access the value of the dictionary item at the current key.

Nesting For Loops in Robot Framework

A nested for loop is a loop inside another loop. In programming, it allows you to iterate through multiple lists or items at once by going through the outer loop first, then through the inner loop for each iteration of the outer loop.

You can nest for loops in Robot Framework using the built-in FOR construct. This allows you to iterate over multiple lists or data sets at the same time.

Here’s an example of how to do this:

*** Test Cases ***
Example Test Case
@{list1}= Create List 1 2 3
@{list2}= Create List A B C
FOR ${item1} IN @{list1}
Log Outer loop item: ${item1}
FOR ${item2} IN @{list2}
Log Inner loop item: ${item2}
END
END
  • In this example of nest For loop, the Create List keyword is used to create two lists, list1 and list2, each with three items.
  • The outer FOR loop iterates through each item in list1, and the inner FOR loop iterates through each item in list2.
  • The Log keyword is then used to print each item to the console.

When nesting FOR loops, include an END statement for each loop. The inner FOR loop must be closed before the outer FOR loop. You can also use Python code within the loops to perform more complex operations.

*** Test Cases ***
Example Test Case
@{list1}= Create List 1 2 3
@{list2}= Create List A B C
FOR ${item1} IN @{list1}
Log Outer loop item: ${item1}
FOR ${item2} IN @{list2}
${result}= Run Keyword And Return Status Should Contain ${item2} ${item1}
Run Keyword If '${result}' == 'True' Log Inner loop item: ${item2}
END
END
  • Here, the Should Contain keyword checks if ${item2} contains ${item1}.
  • The Run Keyword If a keyword is then used to check if the previous keyword returned True.
  • If so, the Log keyword prints ${item2} to the console. This demonstrates how you can use for loops to perform more complex operations in your test cases.

Talk to an Expert

Controlling the execution of a for loop manually

In Robot Framework, you can manually control the flow of a FOR loop using built-in keywords. This allows you to determine when to skip specific iterations or exit the loop early based on custom conditions.

Similar to traditional programming languages like Python, where break and continue statements are used to manage loop execution, Robot Framework provides equivalent keywords:

  • Exit For Loop If — Terminates the loop early if a given condition is met.
  • Continue For Loop If — Skips the current iteration and proceeds to the next one if the condition is evaluated as true.

These keywords help optimize test cases by avoiding unnecessary steps or iterations, especially when specific criteria are already satisfied or invalid.

Example:

FOR    ${item}    IN    @{list}

    ${result}=    Run Keyword And Return Status    Should Be Equal    ${item}    foo

    Continue For Loop If    ${result}

    Log    ${item}

    Exit For Loop If    '${item}' == 'bar'

END

In this example:

  • Continue For Loop If skips the current iteration if ${item} is equal to “foo”.
  • Exit For Loop If stops the loop entirely if ${item} equals “bar”.

BrowserStack Automate Banner

Common Issues and Troubleshooting the For Loop

Several common issues may arise while using FOR loops in Robot Framework, especially if you’re new to it.

1. Incorrect Indentation

Robot Framework is indentation-sensitive. If the loop body is not correctly indented under the FOR keyword, the loop may not execute as expected or could throw an error.

Fix: Ensure all keywords inside the loop are consistently indented and aligned under the FOR block.

2. Missing END Statement (Robot Framework 4.0+)

From Robot Framework 4.0 onwards, loops require an explicit END to indicate the end of the loop body.

Fix: Always add an END statement after the last keyword in the loop.

3. Improper List or Variable Usage

Trying to iterate over an undefined or improperly formatted list can cause the loop to fail.

Fix: Ensure the list is defined correctly and initialized before the loop. Use @{list} syntax for lists.

4. Incorrect Loop Syntax

Using outdated or mixed syntax (such as forgetting IN, or misplacing variables) can lead to execution errors.

Fix: Use the correct format:

 FOR ${item} IN @{list}
   Log ${item}
 END

5. Unintended Infinite Loop Behavior

While Robot Framework doesn’t support traditional while loops, incorrect use of control keywords like Exit For Loop If may cause loops to behave unexpectedly or never exit.

Fix: Double-check the conditions used in the Exit For Loop If to ensure they trigger when expected.

6. Data Type Mismatches

Comparisons in loop conditions can fail silently if the data types are inconsistent, such as comparing a number to a string.

Fix: Ensure that the values being compared are of compatible types. Use type conversion if needed.

Best Practices for Using For Loops in Robot Framework

Follow these best practices when using for loops in Robot Framework to enhance your test case.

  • Keep it simple: The most effective use of for loops is when the iteration logic is simple and easy to understand. Complex or convoluted iteration logic can make your code harder to read and debug.
  • Use descriptive variable names: Use variable names that clearly describe what the variable represents. This can make our code more readable and help prevent errors.
  • Limit the scope of variables: It’s generally a good idea to limit the scope of variables used in for loops to the loop itself. This can help prevent naming conflicts and make our code easier to understand.
  • Avoid modifying the list during iteration: Modifying the list being iterated over during the iteration can lead to unexpected behavior and errors. If we need to modify the list, consider creating a copy before iterating.
  • Use the range() function for iterating over indices: When iterating over a list and needing the index of each item, use the range() function. This allows us to iterate over the indices of the list instead of the values themselves.
  • Use built-in keywords whenever possible: Robot Framework provides several built-in keywords for iterating over lists and dictionaries. Whenever possible, use these keywords instead of implementing your iteration logic.
  • Test thoroughly: As with any code, it’s important to test our for loops thoroughly to ensure they are working as expected. Test cases should include edge and negative scenarios to ensure your code is robust and error-free.

Conclusion

For loops in Robot Framework help automate repetitive actions by allowing you to iterate over lists, dictionaries, or other sequences without duplicating code. Instead of writing the same set of steps multiple times, you can use a loop to execute them dynamically for each input. This reduces redundancy, improves readability, and makes test cases easier to update and scale.

Run your Robot Framework tests on real browsers and devices using BrowserStack to validate them under real-world conditions. With support for parallel execution, CI/CD integration, and debugging tools like video logs and screenshots, BrowserStack enables faster, more accurate testing at scale.

Try BrowserStack for Free

Frequently Asked Questions

1. Is Robot Framework BDD?

Robot Framework is not strictly a BDD (Behavior-Driven Development) framework, but it supports BDD-style testing. You can write test cases in a readable, keyword-driven format similar to Gherkin, but it doesn’t natively use BDD tools like Given/When/Then unless you define them manually or use external libraries.

2. Is Robot Framework better than Selenium?

Robot Framework and Selenium serve different purposes, so one isn’t strictly “better” than the other.

Selenium is a web automation library that provides fine-grained control over web elements and is ideal for developers writing custom automation scripts in languages like Java or Python.

Robot Framework is a higher-level test automation framework that can use Selenium (via libraries like SeleniumLibrary) for web testing. It’s keyword-driven, making it more accessible for testers with minimal coding experience and better suited for larger test suites with reusable logic.

3. What is a timeout in Robot Framework?

A timeout in Robot Framework defines the maximum time a keyword or test case can run. If the execution exceeds the specified time, the keyword or test fails with a timeout error. Timeouts can be set at the test, suite, or keyword level.

4. Which tool is used for Robot Framework?

Robot Framework itself is a tool, but it works with various libraries and external tools depending on the testing needs. The most commonly used tool for web testing is SeleniumLibrary, which integrates Selenium WebDriver with Robot Framework. It also uses AppiumLibrary for mobile testing and Browser for modern web automation.

Tags
Automation Testing Selenium

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord