{"assignment":{"_schema_version":2,"course_id":37,"date_created":"2022-06-28T19:00:00+00:00","date_modified":"2023-09-10T14:19:51.690259+00:00","extra_instructor_files":"","extra_starting_files":"","forked_id":null,"forked_version":null,"hidden":false,"id":1133,"instructions":"## While Patterns\n\n- Numeric While\n- User Input Loop\n- Do-Until Loop\n- Read-Evaluate-Print-Loop\n- Main Game/Server Loop\n- Random Looping\n- List While\n\nWe have seen several loop patterns related to `for` loops.\nThis time, we will see general patterns that are useful for `while` loops.\nThe `while` loop patterns vary much more widely than the `for` loop patterns since the power of a `while` loop is unbounded.\n\n## Numeric While\n\n```python numeric-while-example\ncounter = 100\nwhile counter > 1:\n    counter = counter // 2\n    print(counter)\n```\n\nWe have already talked about how `for` loops are better for iterating over a range of numbers.\nHowever, one immediate advantage for `while` loops is when we need to iterate through numbers non-sequentially.\nIn the code shown here, instead of decreasing by one each time, we are instead halving the value in `counter`.\nThis demonstrates exponential decay and will decrease much more rapidly down to a number less than one.\n\nAny kind of numeric condition can be used with `while` loops, making them more flexible with numbers than `for` loops.\nFor example, you could double the numbers each time (exponential growth), add a value based on user input or increase by a randomly generated number.\nAlthough this is more complicated, there is no replacement when you need to iterate in arbitrary ways.\n\n## Check User Input Loop\n\n```python check-user-input-loop\nuser_input = input(\"What is your age?\")\nwhile not user_input.isdigit():\n    user_input = input(\"Age must be a number! Please try again.\")\nage = int(user_input)\nprint(\"Your numeric age is\", age)\n```\n\nEnd users are notoriously untrustworthy and they often make mistakes.\nA `while` loop can be used to safeguard user input and make sure that they are correctly entering data.\nThe pattern repeatedly takes user input until a condition is satisfied.\nIn the following example, we are repeatedly looping until we are given digits for the `age` variable.\n\n## Do-Until Loop\n\n```python do-until-loop\n# Do-Until Loop\nfinished = False\nwhile not finished:\n    finished = end_condition_expression\n```\n\nThe `while` loop may execute any number of times.\nIf the conditional is initially false, the loop will execute zero times.\nOften, we want the loop to execute at least once before we check the condition.\nThe Do-Until Loop pattern restructures the conditional logic of the `while` loop to delay the conditional check until the end of the first iteration of the loop.\n\n## Example of Do-Until Loop\n\n```python do-until-password\n# Original Loop\npassword = input(\"What is the password?\")\npassword = password.strip()\nwhile password != \"frog\":\n    password = input(\"What is the password?\")\n    password = password.strip()\n\n# Do-Until Loop\nfinished = False\nwhile not finished:\n    password = input(\"What is the password?\")\n    password = password.strip()\n    finished = password != \"frog\"\n```\n\nAs a concrete example, let's compare two programs that get input from the user until they enter a password.\nIn the original version of the loop, we must have the `input` expression before the loop (to give an initial value to `password`) and again inside the loop.\nIf all we needed was to call `input`, that would not be so bad; but we also wanted to call the `strip` method (to remove whitespace) on the `password`.\nIn the Do-Until Loop version, we only need to write the logic for processing the password once\u2014inside of the loop where that processing logically belongs.\n\n## Avoiding Delayed Conditional\n\n```python nonsense-initial-value\n# Appropriate initial Value\npassword = \"WRONG PASSWORD\"\nwhile password != \"frog\":\n    password = input(\"What is the password?\")\n```\n\nIn the previous example, we could also have avoided the redundant `input` call by choosing an appropriate initial value for `password` that doesn't get user input.\nFor example, you could assign the empty string (`\"\"`) or perhaps the garbage string (`\"WRONG PASSWORD\"`).\nThat would allow you to keep the conditional check in the header of the `while` loop.\n\n## Benefit of Delaying the Conditional\n\n```python delayed-conditional-benefit\ndef check_password(given_password: str) -> bool:\n    if given_password == \"frog\":\n        return False\n    elif given_password.strip() == \"frog\":\n        print(\"You added extra whitespace to the password.\")\n    else:\n        print(\"You gave the wrong password.\")\n    return True\n\n# 1) Wrong!\n# Says the user gave the wrong password before they did.\npassword = \"WRONG PASSWORD\"\nwhile check_password(password):\n    password = input(\"What is the password?\")\n\n# 2) Correct!\n# Delays the check until after the user attempts the password\nfailed= False\nwhile not failed:\n    password = input(\"What is the password?\")\n    failed = check_password(password)\n```\n\nHowever, relying on an initial value means the conditional check does occur once before the user even has a chance to enter a password.\nWhen password checking becomes more complicated, this becomes a problem.\nFor example, in the following code, the helper function `check_password` checks if the `given_password` is `\"frog\"`.\nIf not, the function also checks to see if the user accidentally added whitespaces (by using the `strip` method to test if removing the whitespace makes the password correct).\nEither way, a helpful message is printed to the user indicating that that password was wrong.\nHowever, the first version of the `while` loop will incorrectly print this message even before the user has a chance to try entering a password!\nThe second version correctly delays the check until the end.\n\n## Read-Evaluate-Print-Loop\n\n```python repl-example\ncommand = \"\"\nwhile command != \"EXIT\":\n    # Read input from user\n    command = input(\"Input a word, or write EXIT:\")\n    # Evaluate ...\n    # Print the result\n    print(\"You wrote\", command)\n    # Loop back to start of body\n\nprint(\"No more words!\")\n```\n\nAnother use case where a `while` loop is more useful than a `for` loop is when dealing with repeated user input.\nFor instance, the Read-Evaluate-Print-Loop (or REPL) that powers the console uses a `while` loop.\nThe pattern shown here is one way to handle repeated user input.\nThis repeatedly asks for words until the string `\"EXIT\"` is given, at which point it will exit the loop.\n\n## The Evaluate of the REPL\n\n```python repl-evaluate\ncommand = \"\"\nvalue = 5\nwhile command != \"stop\":\n    # Read\n    command = input(\"Write either increase, decrease, or stop\")\n    # Evaluate\n    if command == \"increase\":\n        value += 1\n    elif command == \"decrease\":\n        value -= 1\n    # Print\n    print(\"The value is now:\", value)\n    # Loop!\n```\n\nThe \"Evaluate\" step of the REPL shown above is basically empty; we take a command from the user and print the command back unmodified.\nHowever, this kind of loop is frequently used to handle commands from the user.\nFor example, the following program allows the user to write either \"increase\", \"decrease\", or \"stop\" to manipulate the `value` variable.\n\n## Main Game/Server Loop\n\n* **Main Game Loop**: Intentional infinite loop for long-running applications like servers and games.\n\nOne more kind of user-interaction loop you will occasionally see\u2014but rarely write\u2014is the Main Game Loop.\nThis kind of loop pattern is also sometimes used for web servers and other long-running programs.\nEssentially, this is a loop that is never supposed to end.\nSome programs, such as games or websites, are not really supposed to stop accepting user input.\nThe user is expected to just keep interacting with the game until the game/application/or computer is shut down.\nTherefore, the loop uses the unconditional value `True` for its condition, meaning its body will repeatedly execute forever.\nYou will rarely ever need to create such a program yourself.\nAlmost always, other software or libraries will handle this kind of loop for you, and you will just be expected to write the code that will be executed in the body of the loop.\nHowever, you should be aware that these kinds of infinite loops exist and can be useful in specific cases.\n\n## Random Looping\n\n```python random-looping\nfrom random import randint\n\nfirst_number = randint(0, 10)\nsecond_number = randint(0, 10)\nwhile first_number == second_number:\n    second_number = randint(0, 10)\n\nprint(first_number, second_number)\n```\n\nAnother interesting use case for a `while` loop is to repeatedly pick random numbers.\nThis is less of a specific pattern and more of a general use case, but the principle is the same each time.\nBasically, we use random (also known as stochastic) processes to repeatedly try solutions until one satisfies our constraint.\nIn this example code, we want to pick two different numbers, so we call the `randint` function twice.\nIf the second number is the same as the first number, we repeatedly reroll the second number until the two numbers are different.\nThere are often ways to achieve the same effect using complicated math, but a `while` loop can be a straightforward solution.\nOf course, in the worst-case scenario, we might end up rolling badly each time and waste a lot of time waiting to find a good number.\n\n\n## List While\n\n```python list-while-example\ntargets = [2, 3, 5, 4, -1, 1]\nindex = 0\n\nwhile targets[index] != -1:\n    index = targets[index]\n    print(index)\n```\n\nJust as we saw that a `while` loop can replace a `for` loop for processing numbers, we can also use the `while` loop to process a list.\nThis allows us to process the list in interesting ways that previously were not possible with a simple `for` loop, which just iterates through the sequence from start to finish.\nNow, we can jump to different places in the list.\nAs before, however, you must be careful to avoid accidentally looping forever or indexing out of bounds.\nRemembering to update the current index is very important.\nBefore you run this program, try to predict what will be printed.\n\n## Stepping through the List While Example\n\n1. `index`: `0`\n2. `index`: `2`\n3. `index`: `5`\n4. `index`: `1`\n5. `index`: `3`\n6. `index`: `4`\n7. `index`: `-1`\n\nLet's walk through the example above:\n\nThe initial value of `index` is 0. The conditional checks if the value at that index is equal to `-1`. Since the value at index `0` is `2`, the conditional is true and the loop body executes.\nNext, the `index` variable is updated to be the first element of `targets`, which is again `2`. That value is printed and the loop restarts.\nThen the expression `targets[index]` is calculated using `2` as the index value, which means the third element (`5`). Since that value is not `-1`, the loop continues.\nNow the `index` variable is again updated based on the value at the relevant `index` of `targets; this time the value is `5`. That value is printed and the loop restarts.\nNext, the conditional check looks at index `5` of `targets`, which is `1` (the last element of the list). That is not `-1`, so the loop continues.\nHere, the `index` variable is updated to be `1`, which was the element at index `5`. That value `1` is printed and the loop restarts.\nThis process continues until eventually `index` is `4`, which is where the `-1` is stored in the list.\nAt that point, the conditional expression `targets[index]` evaluates to `-1` and the loop terminates.\n\nThis example is meant to demonstrate just how complex `while` loop iteration can be.\nUnlike a `for` loop, the lists elements do not have to be processed in order, and elements might even be skipped.\nYou must be careful to trace `while` loops very carefully.\n\n## Summary\n\n- There are patterns to using `while` loops like there are with `for` loops, though the `while` loop patterns are a little less rigid.\n- Numeric iteration with a `while` loop can be done with addition, multiplication, exponentiation, and any other math operations.\n- A major use case for `while` loops is to repeatedly process user input until the input matches requirements.\n- A related use case is to use a `while` loop to repeatedly accept commands from a user and execute them.\n- A Do-Until loop reorders a `while` loop so that the conditional check is delayed until after the first execution, ensuring at least one execution of the loop.\n- Sometimes an infinite `while` loop can be useful, such as for a main game loop or another application where the execution should never really end.\n- A `while` loop can be used stochastically to generate numbers that match certain conditions or equations.\n- A `while` loop can be used to iterate through lists and other structures in a non-linear manner.\n\n","ip_ranges":"","name":"10A2) While Loop Patterns Reading","on_change":"","on_eval":"","on_run":"","owner_id":1,"owner_id__email":"acbart@udel.edu","points":0,"public":true,"reviewed":false,"sample_submissions":[],"settings":"{\n  \"header\": \"While Loop Patterns\",\n  \"youtube\": {\n    \"Bart\": \"rzJgYfnj3l0\",\n    \"Amy\": \"q9kHljJQHrs\"\n  },\n  \"video\": {\n    \"Bart\": \"https://blockpy.cis.udel.edu/videos/bakery_time_while_patterns-Bart.mp4\",\n    \"Amy\": \"https://blockpy.cis.udel.edu/videos/bakery_time_while_patterns-Amy.mp4\"\n  },\n  \"summary\": \"\",\n  \"small_layout\": true\n}","starting_code":"","subordinate":true,"tags":[],"type":"reading","url":"bakery_time_while_patterns_read","version":14},"ip":"216.73.216.157","submission":{"_schema_version":3,"assignment_id":1133,"assignment_version":14,"attempts":0,"code":"","correct":false,"course_id":37,"date_created":"2026-05-20T14:01:48.943951+00:00","date_due":"","date_graded":"","date_locked":"","date_modified":"2026-05-20T14:01:48.943951+00:00","date_started":"","date_submitted":"","endpoint":"","extra_files":"","feedback":"","grading_status":"NotReady","id":2036918,"score":0.0,"submission_status":"Started","time_limit":"","url":"submission_url-ed18fe17-a20b-4186-9ddb-f7fa1633d15a","user_id":2044668,"user_id__email":"","version":0},"success":true}
