@extends('template') @section('title') Lab 5 @stop @section('head') @stop @section('content') # Lab 5: Loops {{-- ## [Solutions](/content/labs/lab05/solutions/) --}} {{-- ## [Worksheet solns](https://docs.google.com/document/d/1th9fUY_8kXomeyns4M0gPfdJDPCS1Z5y9DTmSgUHgRw/edit?usp=sharing) --}}
A simple diagram of the flow of a loop A flowchart showing that when entering a loop, the loop condition is evaluated, and if it is false, the program continues past the loop. However, if the condition is true, the loop executes the loop body (conditional code) and then returns to the start of the loop where it proceeds to check the condition again.
 
A more engaging example of a loop in action A short animation of two hands holding an anthropomorphic bao (a kind of Chinese bun); the hands bring the bao closer to the viewpoint as the bao smiles and waves its arms.
[From the Pixar short: Bao]
{{-- @include('/labs/_setup', ['folder' => 'lab05']) --}} @include('/labs/lab05/_toc') ## Big Questions {.bigqs} - *If you want a while loop to stop when one of several conditions is met, how should you write the continuation condition??*
Show Answer In this case, you'd want to continue the loop as long as ALL of the conditions are NOT met, and stop as soon as ANY of them is met. So you can reverse each individual condition using not, and then combine them using and. For example, if you want to stop a loop when either 5 turns have passed or the user guesses correct, you could write: while turns < 5 and guess != answer: ... That condition would become False (stopping the loop) as soon as turns became 5, or as soon as the guess was equal to the answer, whichever happened first.
- *What happens when you use return inside a loop, and why might you want to do that?*
Show Answer As always, if you use return inside a loop, the current function ends, which also exits the loop. You can use this to your advantage to end the loop early if you are looking for something and you find it (for example, does a string contain a certain letter: after you see that letter, you don't need to continue the loop; you can immediately return True). However, you have to be careful: in some cases, you need to process or check each item in your sequence, and an early return would prevent this (for example, finding how many copies of a certain letter a string contains; in this case, we need to check each letter, and cannot return early).
{{-- - *What is a loop variable, and how does it get its values?*
Show Answer A loop variable is the variable created when you create a loop, so if you write for x in 'abc':, x is your loop variable. In each iteration of the loop, the loop variable takes the next value from the sequence that the loop is iterating over (in this example, the letters of the string 'abc').
--}} @stop