{"id":3538,"date":"2023-08-04T19:46:09","date_gmt":"2023-08-04T19:46:09","guid":{"rendered":"https:\/\/www.copahost.com\/blog\/?p=3538"},"modified":"2023-08-05T16:12:39","modified_gmt":"2023-08-05T16:12:39","slug":"while-python","status":"publish","type":"post","link":"https:\/\/www.copahost.com\/blog\/while-python\/","title":{"rendered":"While in Python: The Complete Guide to Repetitive Execution"},"content":{"rendered":"<figure class=\"wp-block-post-featured-image\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1080\" height=\"1080\" src=\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png\" class=\"attachment-post-thumbnail size-post-thumbnail wp-post-image\" alt=\"while python\" style=\"object-fit:cover;\" srcset=\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png 1080w, https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while-300x300.png 300w, https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while-1024x1024.png 1024w, https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while-150x150.png 150w, https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while-768x768.png 768w, https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while-50x50.png 50w\" sizes=\"(max-width: 1080px) 100vw, 1080px\" \/><\/figure>\n\n\n<p>The <strong>while loop<\/strong> is a flow control structure in Python that lets you execute a block of code repeatedly until a certain condition is true. Still, this type of loop is useful when you know exactly how many times you want to run a block of code before it stops.<br><br>We can define a function using just a sentinel and a body of code. However, we check the sentinel condition before each code block execution, and if it is true. We execute in the code. The loop continues executing the code until the condition becomes false. Furthermore, this flow control framework is very powerful and we find its use in many types of programs, from simple scripts to complex applications. The while loop is especially useful in situations where you need to repeat the execution of a block of code until it reaches a certain state.<br><br>In this article, we&#8217;ll explore the use of the while loop in Python, including its syntax, conditions, and flow control. In addition, we will examine practical examples of using the while loop in Python and compare it with other types of loops available in Python. So let&#8217;s start!<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_69_1 ez-toc-wrap-center counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#while_loop_syntax_in_Python\" title=\"while loop syntax in Python\">while loop syntax in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#Simple_examples_of_using_the_while_loop_in_Python\" title=\"Simple examples of using the while loop in Python\">Simple examples of using the while loop in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#While_Loop_Conditions_in_Python\" title=\"While Loop Conditions in Python\">While Loop Conditions in Python<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#boolean_condition\" title=\"boolean condition\">boolean condition<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#comparison_operators\" title=\"comparison operators\">comparison operators<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#border_check\" title=\"border check\">border check<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#while_loop_flow_control_in_Python\" title=\"while loop flow control in Python\">while loop flow control in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#More_advanced_While_examples_in_python\" title=\"More advanced While examples in python\">More advanced While examples in python<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#Example_1_Processing_a_list\" title=\"Example 1: Processing a list.\">Example 1: Processing a list.<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#Example_2_Process_an_array_of_numbers\" title=\"Example 2: Process an array of numbers.\">Example 2: Process an array of numbers.<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#Example_3_Finding_the_number_that_appears_the_fewest_times\" title=\"Example 3: Finding the number that appears the fewest times\">Example 3: Finding the number that appears the fewest times<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#Comparison_with_other_loops_in_Python\" title=\"Comparison with other loops in Python:\">Comparison with other loops in Python:<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#While_loop_example\" title=\"While loop example:\">While loop example:<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#For_loop_example\" title=\"For loop example:\">For loop example:<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/#Example_do-while_loop\" title=\"Example do-while loop:\">Example do-while loop:<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"while_loop_syntax_in_Python\"><\/span>while loop syntax in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The while syntax in Python is quite simple.&nbsp;Likewise, we run a sentinel before each iteration of the loop and run code if the sentinel is true.&nbsp;The loop continues executing the body of code until the sentinel becomes false.<\/p>\n\n\n\n<p>The basic syntax of the while loop in Python is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while condition:\n    # code block to be executed<\/code><\/pre>\n\n\n\n<p>The condition checks a boolean expression before each iteration of the loop.&nbsp;If the condition is true, we execute the block of code between the quotation marks.&nbsp;The loop continues executing the code inside the block until the condition becomes false.<\/p>\n\n\n\n<p>You can add a counter to track the number of loop iterations.&nbsp;To do this, we use a variable and check its value inside the condition.&nbsp;In this example, the loop will execute the code block inside the quotes whenever counter is less than 10. The counter will be incremented in each iteration of the loop, See:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>counter = 0\nwhile counter &lt; 10:\n    # code block to be executed\n    counter += 1<\/code><\/pre>\n\n\n\n<p>In short, the while loop syntax in Python is quite simple and powerful, allowing you to run a block of code repeatedly until a certain condition is true.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Simple_examples_of_using_the_while_loop_in_Python\"><\/span>Simple examples of using the while loop in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The while loop is one of the simplest and most used loops in Python.&nbsp;This way, the code runs repeatedly as long as a given condition is true.&nbsp;To use the while loop, you need to define a condition that will evaluate before each iteration.<\/p>\n\n\n\n<p>Here are some simple examples of how to use the while loop in Python:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Countdown:<\/h4>\n\n\n\n<p>In this example, the condition&nbsp;&nbsp;<code>i &lt; 5<\/code>&nbsp;is evaluated before each iteration, and the value of&nbsp;&nbsp;<code>i<\/code>&nbsp;is incremented by 1 with each iteration.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>i = 0\nwhile i &lt; 5:\n    print(i)\n    i += 1<\/code><\/pre>\n\n\n\n<p>The result is a countdown from 0 to 4.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Checking a keyword:<\/h4>\n\n\n\n<p>In this example, the condition&nbsp; is evaluated before each iteration, and the input prompt is redisplayed if the&nbsp;string<code> word not in [\"key1\", \"key2\"]<\/code>&nbsp;&nbsp;type keyword&nbsp;entered is invalid.&nbsp;The loop will run continuously until you enter a valid keyword.<a href=\"https:\/\/www.homehost.com.br\/blog\/pythondjango\/string-python\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>word = input(\"Insert a keyword: \")\nwhile word not in &#091;\"key1\", \"key2\"]:\n    print(\"Please enter a valid keyword!\")\n    word = input(\"Insert a keyword: \")<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Simple calculator:<\/h4>\n\n\n\n<p>In the example, the condition&nbsp;&nbsp;<code>True<\/code>&nbsp;is used to create an infinite loop.&nbsp;As the user enters an operation, the value of&nbsp;&nbsp;<code>soma<\/code>,&nbsp;&nbsp;<code>subtra\u00e7\u00e3o<\/code>,&nbsp;&nbsp;<code>multiplica\u00e7\u00e3o<\/code>&nbsp;or&nbsp;&nbsp;<code>divis\u00e3o<\/code>&nbsp;is updated and the corresponding output is displayed.&nbsp;If the user enters an invalid operation, the output \u201cInvalid operation!\u201d&nbsp;is displayed and the loop is interrupted with the instruction&nbsp;&nbsp;<code>break<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>while True:\n    s1 = float(input(\"Insert a number: \"))\n    s2 = float(input(\"Insert other number: \"))\n    \n    sum = s1 + s2\n    subtraction = s1 - s2\n    multiplication = s1 * s2\n    division = s1 \/ s2\n    \n    print(\"Sum:\", sum)\n    print(\"Subtraction :\", subtraction)\n    print(\"Multiplication:\", multiplication)\n    print(\"Division:\", division)\n    \n    operation = input(\"Insert a operation: +, -, * or \/ \")\n    if operation == \"+\":\n        s1 = float(input(\"Insert the first number: \"))\n        s2 = float(input(\"Insert the second number: \"))\n        sum = s1 + s2\n        print(\"Sum:\", sum)\n    elif operation == \"-\":\n        s1 = float(input(\"Insert the first number: \"))\n        s2 = float(input(\"Insert the second number: \"))\n        subtraction = s1 - s2\n        print(\"Subtraction:\", subtraction)\n    elif operation == \"*\":\n        s1 = float(input(\"Insert the first number: \"))\n        s2 = float(input(\"Insert the secund number: \"))\n        multiplication = s1 * s2\n        print(\"Multiplication:\", multiplication)\n    elif operation == \"\/\":\n        s1 = float(input(\"Insert the first number: \"))\n        s2 = float(input(\"Insert the second number: \"))\n        division = s1 \/ s2\n        print(\"Division:\", division)\n    else:\n        print(\"Operation invalid!\")\n        break<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Sum length:<\/h4>\n\n\n\n<p>In this example, we have the while loop along with the <a href=\"https:\/\/www.copahost.com\/blog\/len-python\/\">function&nbsp;<code>len<\/code><\/a> where the condition&nbsp;&nbsp;<code>len(soma) &lt; 5<\/code>&nbsp;is evaluated before each iteration.&nbsp;The variable&nbsp;&nbsp;<code><em>soma<\/em><\/code>&nbsp;is initialized to 0, and the iteration will continue to execute until the length of&nbsp;&nbsp;<code>soma<\/code>&nbsp;is equal to 5. As the loop executes, the variable&nbsp;&nbsp;<code><em>soma<\/em><\/code>&nbsp;is incremented by 1 on each iteration, see:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sum = 0\nwhile len(sum) &lt; 5:\n    sum += 1\n    print(sum)<\/code><\/pre>\n\n\n\n<p>The result is a loop that increments the value of&nbsp;&nbsp;<code><em>soma<\/em><\/code>&nbsp;until the length of&nbsp;&nbsp;<code>soma<\/code>&nbsp;is equal to 5.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"While_Loop_Conditions_in_Python\"><\/span>While Loop Conditions in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There are several ways to define a condition for the while loop.&nbsp;Here are some examples:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"boolean_condition\"><\/span>boolean condition<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It&#8217;s the most common way to define a condition for the while loop in Python.&nbsp;The while loop involves a Boolean expression that evaluates to true or false on each iteration of the loop.&nbsp;If the expression is true, the loop continues;&nbsp;if false, the loop ends.&nbsp;<\/p>\n\n\n\n<p>For example, here is the Boolean condition&nbsp;&nbsp;<code>x &lt; 10&nbsp;<\/code>is evaluated on each iteration of the while loop.&nbsp;Since&nbsp;&nbsp;<code>x<\/code>it is less than 10, the expression is true and the loop continues.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 0\nwhile x &lt; 10:\n    print(x)\n    x += 1<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"comparison_operators\"><\/span>comparison operators<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In addition to boolean expressions, we can also use comparison operators to define a condition for the while loop.&nbsp;For example, the condition of the while loop is&nbsp;&nbsp;<code>x &lt; 10 or x &gt; 0<\/code>.&nbsp;The expression&nbsp;&nbsp;<code>x &lt; 10<\/code>is true, so the condition is true, and the loop continues.&nbsp;When it&nbsp;&nbsp;<code>x<\/code>reaches 10, the expression&nbsp;&nbsp;<code>x &gt; 0<\/code>is true and the condition is again true, see below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 0\nwhile x &lt; 10 or x &gt; 0:\n    print(x)\n    x += 1<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"border_check\"><\/span>border check<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In addition to comparing to a specific number, you can use bounds checking to define a condition for the while loop.&nbsp;For example, the condition of the while loop is&nbsp;&nbsp;<code>x &lt; 10 or x &gt;= -5<\/code>.&nbsp;The expression&nbsp;&nbsp;<code>x &lt; 10<\/code>is true, so the condition is true, and the loop continues:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 0\nwhile x &lt; 10 or x &gt;= -5:\n    print(x)\n    x += 1<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"while_loop_flow_control_in_Python\"><\/span>while loop flow control in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The while loop flow control in Python is a flow control structure that executes a sequence of statements repeatedly until a condition is true.&nbsp;While the while loop is simple in concept. We can use it in complex ways to manage loop execution and ensure that the condition is true only once.<\/p>\n\n\n\n<p>A common strategy to ensure that the condition is true only once is to use a control&nbsp;<a href=\"https:\/\/www.geeksforgeeks.org\/python-variables\/\">variable<\/a>&nbsp;to track the number of loop iterations.&nbsp;For example, a control variable&nbsp;&nbsp;<code>i<\/code>is used to track the number of iterations of the while loop.&nbsp;When it&nbsp;&nbsp;<code>i<\/code>reaches 5, the loop condition is stopped using the keyword&nbsp;&nbsp;<code>break<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>i = 0\nwhile i &lt; 10:\n    if i == 5:\n        break\n    i += 1<\/code><\/pre>\n\n\n\n<p>This way, the condition is true only once, when&nbsp;&nbsp;<code>i<\/code>it is equal to 5.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"More_advanced_While_examples_in_python\"><\/span>More advanced While examples in python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The while loop is a versatile solution to many problems in different contexts.&nbsp;In that vein, here are some examples of how we use the loop to solve specific problems like processing lists and matrices.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_1_Processing_a_list\"><\/span>Example 1: Processing a list.<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In this example, we use the while loop to increment all values \u200b\u200bin a list.&nbsp;We use the variable&nbsp;&nbsp;<code><em>count<\/em><\/code>to track the number of elements in&nbsp;<em><code>lst<\/code>&nbsp;<\/em>and it is updated on each iteration of the while loop.&nbsp;So when it&nbsp;&nbsp;<em><code>count<\/code>&nbsp;<\/em>reaches the length of&nbsp;&nbsp;<code><em>lst<\/em><\/code>, the loop condition is true and the loop terminates.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>lst = &#091;1, 2, 3, 4, 5]\ncount = 0\nwhile count &lt; len(lst):\n    lst&#091;count] += 1\n    count += 1\nprint(lst)<\/code><\/pre>\n\n\n\n<p>The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#091;2, 3, 4, 5, 6]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_2_Process_an_array_of_numbers\"><\/span>Example 2: Process an array of numbers.<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Using a while loop, we can process an array of numbers by multiplying each element by its position in the array and adding 1 to the column.&nbsp;Therefore, we process the matrix in reverse. Multiplying each element by its position in the matrix and adding 1 to the column.&nbsp;Look:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Create a 3x3 matrix of numbers\nmatrix = &#091;&#091;1, 2, 3], &#091;4, 5, 6], &#091;7, 8, 9]]\n\n# Loop while\nwhile True:\n    # Loop through columns\n    for column in matrix:\n        # Multiply each element by the column\n        multiplying = 1\n        for element in column:\n            multiplying *= element\n        # Add 1 to column\n        for additional_column in matrix:\n            additional_column.append(1)\n        # Print the current matrix\n        print(matrix)<\/code><\/pre>\n\n\n\n<p>The result of running this code is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#091;&#091;1, 2, 3], &#091;14, 15, 16], &#091;21, 22, 23]]\n&#091;&#091;2, 4, 6], &#091;15, 18, 21], &#091;22, 27, 32]]\n&#091;&#091;3, 6, 9], &#091;18, 24, 27], &#091;30, 36, 42]]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_3_Finding_the_number_that_appears_the_fewest_times\"><\/span>Example 3: Finding the number that appears the fewest times<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It is possible to find the number that appears the fewest times in a list. As shown below for an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Create a list of numbers\nlist = &#091;1, 2, 3, 2, 1, 4, 3, 2]\n\n# Initialize counter to 0\ncounter = 0\n\n# Initialize the smallest number to None\nminor_number = None\n\n# Loop while\nwhile counter &lt; len(list):\n    # Check if the number has already been counted\n    if counter not in counter_list:\n        # Update minor number\n        minor_number = counter \n\n    # increment the counter\n    counter += 1\n\n# Prints the result\nprint(\"The number that appears the fewest times is:\", minor_number)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Comparison_with_other_loops_in_Python\"><\/span>Comparison with other loops in Python:<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The while loop is one of the main loop types in Python, which allows you to execute a block of code repeatedly as long as a specific condition is true.&nbsp;However, Python also offers other types of loops, such as the&nbsp;<a href=\"https:\/\/www.copahost.com\/blog\/for-python\/\">for loop in python<\/a>&nbsp;and the do-while loop. Which have some similarities and differences in terms of their syntax and usage.<\/p>\n\n\n\n<p>However, below, we&#8217;ll look at the similarities and differences between the while loop, the for loop, and the do-while loop in Python:<\/p>\n\n\n\n<p>Similarities:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The three types of loops \u2013 while, for, and do-while \u2013 allow for the repeated execution of a block of code until we reach a specific condition.<\/li>\n\n\n\n<li>It is possible that we use the three types of loop \u2013 while, for and do-while \u2013 in conjunction with other flow control structures, such as if\/else and switch\/case.<\/li>\n\n\n\n<li>All three types of loops can process sequences of data such as lists, tuples, and strings.<\/li>\n<\/ul>\n\n\n\n<p>Differences:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The while loop executes while a specific condition is true. The for loop executes while the condition is true, and the do-while loop executes while the condition is true or the function&#8217;s output value is other than None.<\/li>\n\n\n\n<li>The while loop executes in the simplest and most straightforward way. Whereas the for loop requires you to explicitly specify control variables such as start and end.&nbsp;The do-while loop has an intermediate syntax between the while loop and the for loop.<\/li>\n\n\n\n<li>The do-while loop is best suited for situations where the condition is true on the first iteration of the loop while. Is best for situations where the condition does not become true on the first iteration of the loop.<\/li>\n<\/ul>\n\n\n\n<p>The following are examples to illustrate the difference between the three loop types:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"While_loop_example\"><\/span>While loop example:<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>We use the while loop to print the values \u200b\u200bof x from 0 to 4. The loop condition, ,&nbsp;&nbsp;<code>x &lt; 5<\/code>is true the first time the loop executes, which causes the code block inside the loop to execute.&nbsp;After the block of code executes, the variable&nbsp;&nbsp;<code>x<\/code>&nbsp;is incremented by 1 and the loop condition is checked again.&nbsp;This occurs repeatedly until the condition&nbsp;&nbsp;<code>x &lt; 5<\/code>&nbsp;becomes false, that is, when&nbsp;&nbsp;<code>x<\/code>&nbsp;it reaches the value 5, See:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 0\nwhile x &lt; 5:\n    print(x)\n    x += 1<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"For_loop_example\"><\/span>For loop example:<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>We use the&nbsp;for loop in Python&nbsp;to print the values \u200b\u200bof&nbsp;&nbsp;<code>range(5)<\/code>, which creates a sequence of numbers from 0 to 4. In this way, the structure&nbsp;&nbsp;<code>for<\/code>&nbsp;is using the&nbsp;<a href=\"https:\/\/www.copahost.com\/blog\/python-range\/\">method&nbsp;<code>range<\/code><\/a><code> em Python<\/code>&nbsp;&nbsp;to generate a sequence of numbers, and we use the variable&nbsp;&nbsp;<code>i<\/code>to represent each number in the sequence.&nbsp;Therefore, the condition&nbsp;&nbsp;<code>i &lt; 5<\/code>&nbsp;is true for each value of&nbsp;&nbsp;<code>i<\/code>&nbsp;in the sequence, which causes the block of code inside the loop to be executed once for each value of&nbsp;&nbsp;<code>i<\/code>, See:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for i in range(5):\n    print(i)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_do-while_loop\"><\/span>Example do-while loop:<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>We use the do-while loop to print the values \u200b\u200bof&nbsp;&nbsp;<code>x<\/code>&nbsp;0 through 4. The loop condition,&nbsp;&nbsp;<code>x &lt; 5<\/code>, is true the first time the loop executes, which causes the code block inside the loop to execute.&nbsp;Right after the block of code executes, the variable&nbsp;&nbsp;<code>x<\/code>&nbsp;is incremented by 1 and the loop condition is checked again.&nbsp;Thus, this occurs repeatedly until the condition&nbsp;&nbsp;<code>x &lt; 5<\/code>&nbsp;becomes false, that is, when&nbsp;&nbsp;<code>x<\/code>&nbsp;it reaches the value 5.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = 0\ndo:\n    print(x)\n    x += 1\nwhile x &lt; 5<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Conclusion<\/h4>\n\n\n\n<p>In summary, the while loop is a very powerful flow control structure in Python that allows you to execute a block of code repeatedly until a certain condition is true.&nbsp;It&#8217;s easy using the while loop, as we can define it with just a sentinel and a body of code.<\/p>\n\n\n\n<p>Thus, the while loop becomes a better choice when we have prior knowledge of how many times we want to execute a block of code before stopping.&nbsp;It is especially useful in situations where we need to repeat code execution until we reach a certain state.<\/p>\n\n\n\n<p>In this article, we discuss using the while loop in Python, including its syntax, conditions, and flow control, and provide practical examples of using the while loop in Python.&nbsp;When comparing with other types of loops available in Python. We realized that the while loop is a versatile and powerful flow control structure that we find in many types of programs.<\/p>\n\n\n\n<p>We hope this article helped you better understand the use of the while loop in Python and how you can apply it in your own program creations.&nbsp;Also, learn about&nbsp;Switch Case&nbsp;and&nbsp;<a href=\"https:\/\/www.copahost.com\/blog\/scan-python\/\">Scan in Python<\/a>&nbsp;!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The while loop is a flow control structure in Python that lets you execute a block of code repeatedly until a certain condition is true. Still, this type of loop is useful when you know exactly how many times you want to run a block of code before it stops. We can define a function [&hellip;]<\/p>\n","protected":false},"author":17,"featured_media":3557,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[174],"tags":[],"class_list":["post-3538","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v23.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>While in Python: The Complete Guide to Repetitive Execution - Copahost<\/title>\n<meta name=\"description\" content=\"Learn about the while function in Python, a powerful flow control framework that lets you run a block of code repeatedly.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.copahost.com\/blog\/while-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"While in Python: The Complete Guide to Repetitive Execution - Copahost\" \/>\n<meta property=\"og:description\" content=\"Learn about the while function in Python, a powerful flow control framework that lets you run a block of code repeatedly.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.copahost.com\/blog\/while-python\/\" \/>\n<meta property=\"og:site_name\" content=\"Copahost\" \/>\n<meta property=\"article:published_time\" content=\"2023-08-04T19:46:09+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-08-05T16:12:39+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1080\" \/>\n\t<meta property=\"og:image:height\" content=\"1080\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Schenia T\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Schenia T\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/\"},\"author\":{\"name\":\"Schenia T\",\"@id\":\"https:\/\/www.copahost.com\/blog\/#\/schema\/person\/2efb96f9dfaf6162f347abcd06b1429f\"},\"headline\":\"While in Python: The Complete Guide to Repetitive Execution\",\"datePublished\":\"2023-08-04T19:46:09+00:00\",\"dateModified\":\"2023-08-05T16:12:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/\"},\"wordCount\":2053,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png\",\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.copahost.com\/blog\/while-python\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/\",\"url\":\"https:\/\/www.copahost.com\/blog\/while-python\/\",\"name\":\"While in Python: The Complete Guide to Repetitive Execution - Copahost\",\"isPartOf\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png\",\"datePublished\":\"2023-08-04T19:46:09+00:00\",\"dateModified\":\"2023-08-05T16:12:39+00:00\",\"description\":\"Learn about the while function in Python, a powerful flow control framework that lets you run a block of code repeatedly.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.copahost.com\/blog\/while-python\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage\",\"url\":\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png\",\"contentUrl\":\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png\",\"width\":1080,\"height\":1080,\"caption\":\"while python\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.copahost.com\/blog\/while-python\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.copahost.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"While in Python: The Complete Guide to Repetitive Execution\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.copahost.com\/blog\/#website\",\"url\":\"https:\/\/www.copahost.com\/blog\/\",\"name\":\"Copahost\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.copahost.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.copahost.com\/blog\/#organization\",\"name\":\"Copahost\",\"url\":\"https:\/\/www.copahost.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.copahost.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2016\/03\/copahostlogo.png\",\"contentUrl\":\"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2016\/03\/copahostlogo.png\",\"width\":223,\"height\":40,\"caption\":\"Copahost\"},\"image\":{\"@id\":\"https:\/\/www.copahost.com\/blog\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.copahost.com\/blog\/#\/schema\/person\/2efb96f9dfaf6162f347abcd06b1429f\",\"name\":\"Schenia T\",\"description\":\"Data scientist, passionate about technology tools and games. Undergraduate student in Statistics at UFPB. Her hobby is binge-watching series, enjoying good music working or cooking, going to the movies and learning new things!\",\"url\":\"https:\/\/www.copahost.com\/blog\/author\/schenia\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"While in Python: The Complete Guide to Repetitive Execution - Copahost","description":"Learn about the while function in Python, a powerful flow control framework that lets you run a block of code repeatedly.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.copahost.com\/blog\/while-python\/","og_locale":"en_US","og_type":"article","og_title":"While in Python: The Complete Guide to Repetitive Execution - Copahost","og_description":"Learn about the while function in Python, a powerful flow control framework that lets you run a block of code repeatedly.","og_url":"https:\/\/www.copahost.com\/blog\/while-python\/","og_site_name":"Copahost","article_published_time":"2023-08-04T19:46:09+00:00","article_modified_time":"2023-08-05T16:12:39+00:00","og_image":[{"width":1080,"height":1080,"url":"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png","type":"image\/png"}],"author":"Schenia T","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Schenia T","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.copahost.com\/blog\/while-python\/#article","isPartOf":{"@id":"https:\/\/www.copahost.com\/blog\/while-python\/"},"author":{"name":"Schenia T","@id":"https:\/\/www.copahost.com\/blog\/#\/schema\/person\/2efb96f9dfaf6162f347abcd06b1429f"},"headline":"While in Python: The Complete Guide to Repetitive Execution","datePublished":"2023-08-04T19:46:09+00:00","dateModified":"2023-08-05T16:12:39+00:00","mainEntityOfPage":{"@id":"https:\/\/www.copahost.com\/blog\/while-python\/"},"wordCount":2053,"commentCount":0,"publisher":{"@id":"https:\/\/www.copahost.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage"},"thumbnailUrl":"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png","articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.copahost.com\/blog\/while-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.copahost.com\/blog\/while-python\/","url":"https:\/\/www.copahost.com\/blog\/while-python\/","name":"While in Python: The Complete Guide to Repetitive Execution - Copahost","isPartOf":{"@id":"https:\/\/www.copahost.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage"},"image":{"@id":"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage"},"thumbnailUrl":"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png","datePublished":"2023-08-04T19:46:09+00:00","dateModified":"2023-08-05T16:12:39+00:00","description":"Learn about the while function in Python, a powerful flow control framework that lets you run a block of code repeatedly.","breadcrumb":{"@id":"https:\/\/www.copahost.com\/blog\/while-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.copahost.com\/blog\/while-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.copahost.com\/blog\/while-python\/#primaryimage","url":"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png","contentUrl":"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2023\/08\/while.png","width":1080,"height":1080,"caption":"while python"},{"@type":"BreadcrumbList","@id":"https:\/\/www.copahost.com\/blog\/while-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.copahost.com\/blog\/"},{"@type":"ListItem","position":2,"name":"While in Python: The Complete Guide to Repetitive Execution"}]},{"@type":"WebSite","@id":"https:\/\/www.copahost.com\/blog\/#website","url":"https:\/\/www.copahost.com\/blog\/","name":"Copahost","description":"","publisher":{"@id":"https:\/\/www.copahost.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.copahost.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.copahost.com\/blog\/#organization","name":"Copahost","url":"https:\/\/www.copahost.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.copahost.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2016\/03\/copahostlogo.png","contentUrl":"https:\/\/www.copahost.com\/blog\/wp-content\/uploads\/2016\/03\/copahostlogo.png","width":223,"height":40,"caption":"Copahost"},"image":{"@id":"https:\/\/www.copahost.com\/blog\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/www.copahost.com\/blog\/#\/schema\/person\/2efb96f9dfaf6162f347abcd06b1429f","name":"Schenia T","description":"Data scientist, passionate about technology tools and games. Undergraduate student in Statistics at UFPB. Her hobby is binge-watching series, enjoying good music working or cooking, going to the movies and learning new things!","url":"https:\/\/www.copahost.com\/blog\/author\/schenia\/"}]}},"_links":{"self":[{"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/posts\/3538","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/users\/17"}],"replies":[{"embeddable":true,"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/comments?post=3538"}],"version-history":[{"count":19,"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/posts\/3538\/revisions"}],"predecessor-version":[{"id":3578,"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/posts\/3538\/revisions\/3578"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/media\/3557"}],"wp:attachment":[{"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/media?parent=3538"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/categories?post=3538"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.copahost.com\/blog\/wp-json\/wp\/v2\/tags?post=3538"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}