Master ‘For Loops’ in Robot Framework
Related Product On This Page What is the Robot Framework?May 27, 2026 · 22 min read · Testing Guide
I didn ’ t imagine much about Robot Framework ’ s loops until a test retinue became impossible to maintain. One minor update meant editing the same steps in multiple places, and every modification introduced new mistakes. Something wasn ’ t scaling—and grummet turned out to be the missing part. Once I explored how Robot Framework iterates through lists, dictionary, and ranges, I realized I could supersede entire sections of duplicated steps with a few clean, pliant loops. It change how I approached automation entirely. Basic Syntax of ‘ For Loop ’ in Robot Framework: Types of For Loop in Robot Framework: This usher walk through how those loops actually work, with practical examples and patterns that do test automation faster and far easy to manage. is an open-source mechanisation model designed for exam automation and robotic process automation (RPA). It uses a simple, keyword-driven syntax that makes make and managing trial example easy, even for exploiter with minimal programming cognition. It & # 8217; s widely used for,, and across different platforms and engineering. The for loop Robot fabric is to automatise repetitive tasks, reduce manual sweat, and make trial playscript more effective and maintainable. For loops in Robot Framework can be expend in various scenario, such as restate over a list of test information values to run the same test lawsuit with different remark argument or restate over a set of UI elements to perform the like action on each element. Key factors for using For cringle in Robot Framework: - A FOR loop in Robot Framework is a control construction that allows us to repeat a set of actions a certain routine of times, or to retell over a list or reach of values. The basic syntax of a golem framework for loop model is as follow: You can also use Python & # 8217; s built-in scope function to iterate a specific routine of times. Here is an example: Robot framework for loop is employ to repeat a set of measure a certain number of times or for a specific range of values. The basic syntax for a for loop robot framework is as follow: For example, if we receive a list of usernames and passwords to try login functionality, we can use a for iteration to iterate through the listing and execute the login test with each set of credentials. 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 example, if a test case requires a unique e-mail address each time it is executed, we can use a for loop to give a list of unique email addresses and accomplish the test example with each email address. These are just a few examples of the many style for eyelet can be used in Robot Framework for real-time use cases. The versatility of the for loop syntax let us to hold them in a wide range of testing scenario. Robot Framework supports multiple loop fluctuation, each plan for specific data structure and loop needs. Below are the four nucleus loop types, with details on when and why each is used. FOR IN Loop The FOR INgrommet is the almost commonly used loop type and is ideal for iterating over listing, tuples, or any collection of values. It allows executing the same set of keywords for every particular in a sequence. This iteration is often use for validating multiple remark, pass repeated UI interactions, or process datasets. Its flexibility makes it the default choice for most test scenarios where item demand to be handled severally. FOR IN RANGE Loop The FOR IN RANGEgrommet is employ when a test requires fixed repetition or numerical iteration. It behave likewise to Python ’ s range () function, generating a serial of integers from a starting point to an endpoint. This loop is helpful for running a specific number of retries, action stress tests with repeated actions, or perform index-based operation without trust on an existing list. FOR IN ZIP Loop The FOR IN ZIPloop allows simultaneous iteration over two or more lists, pairing elements based on their view. This is especially useful for validating input–output pairs, combining UI fields with expected results, or driving test steps where related data must be processed together. If one list is shorter, the loop block at the end of the shortest succession, ensuring synchronized iteration. FOR IN ENUMERATE Loop The FOR IN ENUMERATEloop provides both the index and the value of each element in the list. It is suited for scenario where the position of the item matters—such as corroborate table quarrel, generating dynamical identifiers, or debugging test data topic. The index can likewise be used to trigger conditional logic, making this loop eccentric utile for more advanced flow control inside tryout cases. Read More: In the Robot Framework, you can use For Loops with lists habituate the built-in FOR loop construct in combination with Python codification. Here ’ s an example of how to do this: Define your list in a test case or keyword: In the above exemplar, the Create List keyword creates a list with detail item1, item2, and item3. The FOR loop then iterate through each particular in the inclination and logs the particular to the console. You can also use Python code within the FOR grommet to manipulate the list items: Note that the ${}syntax is used to access variable in Robot Framework. In the Python code within the FOR loop, the $ {index} variable is used to approach the current power of the list, and the$ {my_list [$ {index}]}syntax is used to access the value of the list detail at the current index. 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 lawsuit or keyword: For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users. You can too use Python codification within the FOR grommet to manipulate the dictionary items: 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 entree the value of the dictionary point at the current key. A nested for loop is a loop inside another eyelet. In programming, it allows you to iterate through multiple lists or items at formerly by going through the outer loop firstly, 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 inclination or data sets at the same time. Here & # 8217; s an example of how to do this: When nesting FOR loops, include an END statement for each iteration. 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. Running nested loops often means fulfill complex test feed across multiple environments. do this scalable by pass each loop iteration on real browsers and OS combinations, helping teams uncover UI and workflow issues that only appear in real user conditions. For loops in Robot Framework are widely used to deal insistent validations, iterate through datasets, and execute the same action across multiple environments or input values. The examples below instance how loops solve real test problems across UI, API, and data-driven scenario. Validating Multiple Form Fields When a page contains several remark fields, a eyelet allows validating each field without duplicating steps. This avoids three separate test blocks and centralizes the validation. Running the Same UI Test Across Multiple Browsers A single for loop can cycle through different BrowserStack environments to get cross-browser issues betimes. Teams often use this figure with BrowserStack Automate to scale multi-browser examination. Data-Driven API Testing Testing multiple payloads becomes simple with a grummet. This reduces repeated API test cases and simplifies updates. Verifying Table Rows Loops help validate dynamic tables where the number of rows can change. This work good for dashboards, account, and admin venire. Bulk Upload or Multi-Step Flows If the test must upload multiple files or recur a workflow, a loop get the succession clean and reusable. Great for regression tests involving multiple data samples. Stress Testing with Range Loops A FOR IN RANGEeyelet helps repeat an activity more times than manually virtual. Utilitarian for negative testing and rate-limiting validations. Read More: In Robot Framework, you can manually control the flow of a FOR grommet using built-in keywords. This allows you to influence when to skip specific iterations or exit the grommet early based on custom conditions. Similar to traditional programming languages like Python, where shift and continue statements are used to negociate loop execution, Robot Framework provides tantamount keywords: These keywords help optimize test suit by avoiding unnecessary stairs or looping, specially when specific criteria are already satisfied or invalid. Example: In this representative: Read More: Several common issues may arise while using FOR loop in Robot Framework, particularly if you ’ re new to it. 1. Incorrect Indentation Robot Framework is indentation-sensitive. If the iteration body is not correctly indent under the FOR keyword, the loop may not fulfill as expected or could throw an error. Fix:Ensure all keywords inside the grommet are consistently indented and adjust under the FOR block. 2. Missing END Statement (Robot Framework 4.0+) From Robot Framework 4.0 onwards, loops require an expressed END to indicate the end of the eyelet body. Fix:Always add an END statement after the concluding keyword in the loop. 3. Improper List or Variable Usage Trying to ingeminate over an undefined or improperly formatted tilt can cause the loop to fail. Fix: Ensure the tilt is defined correctly and initialized before the iteration. Use @ {list} syntax for tilt. 4. Incorrect Loop Syntax Using outdated or mixed syntax (such as forgetting IN, or lose variable) can lead to execution errors. Fix:Use the right format: 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 release. Fix:Double-check the conditions used in the Exit For Loop If to see they trigger when expected. 6. Data Type Mismatches Comparisons in loop weather can fail silently if the datum types are inconsistent, such as equate a number to a string. Fix: Ensure that the values being compared are of compatible character. Use type conversion if needed. Follow these best practices when using for cringle in Robot Framework to enhance your exam case. Loopsin Robot Framework are utilise when test steps need to be repeated for multiple inputs, datasets, or environments. They are ideal for ingeminate through lists, ranges, or paired values and help eliminate double the like keyword episode multiple multiplication. Loops shine in data-driven scenarios—validating form fields, checking multiple API payloads, or escape the like UI interactions across different browser. User-defined keywords, on the former hand, are best suited for group related steps into a reusable unit. They help organize test cases, reduce welter, and maintain logic in one place instead of repeating long succession. Keywords make the test suite more readable and allow central updates: change one keyword update every test that uses it. In drill, iteration and user-defined keywords employment better together. A loop handles iteration, while the repeated steps inside it are package into a clean, reclaimable keyword. This approach keep tests scalable, easygoing to maintain, and far less error-prone. Loops vs. User-Defined Keywords in Robot Framework Read More: For loops in Robot Framework assistance automatize insistent actions by let you to ingeminate over lists, lexicon, or early sequences without duplicating code. Instead of publish the same set of steps multiple times, you can use a grommet to execute them dynamically for each input. This reduces redundance, meliorate readability, and makes test cases easygoing to update and scale. Run your Robot Framework tests on real browsers and devices utilise to validate them under real-world conditions. With support for parallel execution, integration, and debugging tools like video logs and screenshots, BrowserStack enables fast, more exact testing at scale. A for loop in Robot Framework is a control structure that allows repeating a set of keywords for each item in a leaning, dictionary, range, or paired dataset. It helps reduce duplicate steps and do tests more maintainable. A canonical iteration use theFOR … IN syntax. You define a list of values and execute the same keywords for each item. Proper indentation andENDare required to distinguish the eyelet boundary. FOR IN iterates through items in a list, whileFOR IN RANGEgenerates a successiveness of numbers for a fixed number of repetitions. RANGE loops are useful for accent tests or index-based operations. Yes. Robot Framework providesFOR IN ZIP, which iterate through two or more lists in parallel, pairing ingredient by position. This is helpful for input–output validation or form-field mapping. Use FOR IN ENUMERATEwhen you need both the value and its index. It is useful for table establishment, row-level assertions, and debugging inclination positions during tryout performance. Yes. Nested loops allow multi-level looping, such as validating multi-dimensional datasets or running the like checks across combination of examination stimulus. However, they should be managed carefully to sustain readability. Robot Framework does not have a built-inbreak, but you can check execution apply inlineIFconditions and keywords likeExit For Loop If(usable in new versions) to stop or cut loop. Common issue include incorrect indent, missingEND, wrong variable types, or passing an empty list. Validating data before the loop starts facilitate avoid silent failures. Yes. Loops inside user keywords are mutual for creating reusable validation logic, input processors, or structured workflows. This keeps test cases clean and concise. On This Page # Ask-and-Contributeabout this theme with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Related Product
How to use for iteration in Robot Framework in 2026
Overview
FOR $ {detail} IN @ {lean} & lt; keywords using $ {item} & gt; ENDWhat is the Robot Framework?
What is the Purpose of For loops in Robot Framework?
Want stable Robot runs?
How to write a for iteration in Robot Framework?
* * * Variables * * * @ {list} item1 item2 item3 * * * Test Cases * * * Example Test FOR $ {item} IN @ {list} Log $ {detail} # Perform other actions on $ {item} END* * * Test Cases * * * Example Test FOR $ {i} IN RANGE 5 Log $ {i} ENDBasic Syntax of For Loops in the Robot Framework
FOR $ {index} IN RANGE $ {start} $ {end} [$ {stride}] [Keyword or Steps] [Keyword or Steps] [Keyword or Steps]FOR $ {user} $ {word} IN ZIP @ {usernames} @ {passwords} Input Text $ {username_field} $ {user} Input Text $ {password_field} $ {word} Click Button $ {login_button} Wait Until Page Contains $ {welcome_message} Click Button $ {logout_button}FOR $ {product} $ {terms} IN ZIP @ {products} @ {prices} $ {subtotal} = Evaluate $ {price} * $ {quantity} $ {full} += $ {subtotal}FOR $ {i} IN RANGE 1 $ {number_of_tests} $ {email} = Generate Unique Email Run Keyword And Continue On Failure Submit Registration Form $ {e-mail} $ {parole}FOR $ {i} IN RANGE 1 10 Click Button $ {random_button} Wait Until Page Contains Element $ {random_element} Click Button $ {back_button}Types of For Loops in Robot Framework
* * * Test Cases * * * For In Example @ {items} = Create List Apple Banana Orange FOR $ {item} IN @ {items} Log $ {item} END* * * Test Cases * * * For In Range Example FOR $ {i} IN RANGE 0 5 Log Iteration $ {i} END* * * Test Cases * * * For In Zip Example @ {name} = Create List John Sara Alex @ {roles} = Create List Admin Editor Viewer FOR $ {gens} $ {role} IN ZIP @ {name} @ {use} Log $ {gens} has role $ {role} END* * * Test Cases * * * For In Enumerate Example @ {particular} = Create List Alpha Beta Gamma FOR $ {index} $ {detail} IN ENUMERATE @ {items} Log Index: $ {indicator}, Item: $ {particular} ENDUsing For Loops with Lists in the Robot Framework
* * * Test Cases * * * Example Test Case $ {my_list} = Create List item1 item2 item3 FOR $ {item} IN @ {my_list} Log $ {item} END* * * Test Cases * * * Example Test Case $ {my_list} = Create List item1 item2 item3 FOR $ {point} IN @ {my_list} Log $ {item} ENDUsing For Loops with Dictionaries in Robot Framework
* * * 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* * * 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}Nesting For Loops in Robot Framework
* * * 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 particular: $ {item2} END END* * * Test Cases * * * Example Test Case @ {list1} = Create List 1 2 3 @ {list2} = Create List A B C FOR $ {item1} IN @ {list1} Log Outer loop point: $ {item1} FOR $ {item2} IN @ {list2} $ {result} = Run Keyword And Return Status Should Contain $ {item2} $ {item1} Run Keyword If ' $ {result} ' == 'True ' Log Inner loop point: $ {item2} END ENDReal-World Use Cases & amp; Examples of ‘ For Loop ’ in Robot Framework
* * * Test Cases * * * Validate Multiple Form Fields Open Browser https: //example.com/form chrome @ {battlefield} = Create List username netmail sound FOR $ {field} IN @ {fields} Element Should Be Visible id= $ {field} Element Should Be Enabled id= $ {field} END Close Browser* * * Test Cases * * * Cross Browser Test @ {browsers} = Create List chrome firefox edge FOR $ {browser} IN @ {browser} Open Browser https: //shop.com $ {browser} Page Should Contain Shop Now Close Browser END* * * Test Cases * * * API Payload Validation @ {payloads} = Create List {`` id '' :1} {`` id '' :2} {`` id '' :3} FOR $ {payload} IN @ {payloads} $ {response} = Post Request api /user $ {payload} Should Be Equal As Integers $ {response.status_code} 200 END* * * Test Cases * * * Validate Table Rows @ {rows} = Get WebElements //table/tbody/tr FOR $ {row} IN @ {rows} $ {text} = Get Text $ {row} Should Not Be Empty-bellied $ {schoolbook} END* * * Test Cases * * * Upload Multiple Files @ {files} = Create List file1.png file2.pdf file3.jpg FOR $ {file} IN @ {file} Choose File id=upload $ {CURDIR} / $ {file} Click Button id=submit Page Should Contain Upload Successful END* * * Test Cases * * * Stress Test Login FOR $ {i} IN RANGE 1 20 Attempt Login With Invalid Credentials Page Should Contain Invalid username or password ENDControlling the execution of a for loop manually
FOR $ {point} IN @ {list} $ {result} = Run Keyword And Return Status Should Be Equal $ {detail} foo Continue For Loop If $ {resolution} Log $ {item} Exit For Loop If ' $ {item} ' == 'bar' ENDCommon Issues and Troubleshooting the For Loop
FOR $ {item} IN @ {tilt} Log $ {particular} ENDBest Practices for Using For Loops in Robot Framework
Loops vs. User-Defined Keywords in Robot Framework
Aspect Loops User-Defined Keywords Purpose Repeat a set of steps for multiple items or iterations Group related step into reusable, maintainable keywords Best Use Case Data-driven testing, iterating over lean, ranges, or paired values Organizing workflows, trim duplicate, improving readability When to Choose When the same action must run multiple times with different input When steps organize a ordered unit that appears in multiple examination Advantages Eliminates repetitive blocks, supports dynamic input processing Centralized logic, cleaner test cases, easygoing update Limitations Can become hard to read if loops grow composite or nested Not ideal for large sets of insistent activeness without eyelet Typical Pattern Loop iterates → keywords execute inside each iteration Keyword encapsulates logic → can be called inwardly loops Ideal Together Run intertwine for iteration across datasets Use keywords to keep grummet contented clean and recyclable Conclusion
FAQs
Related Guides
Automate This With SUSA
Test Your App Autonomously