Lab 5: Loops
|A simple diagram of the flow of a loop|
|A more engaging example of a loop in action||
[From the Pixar short: Bao]
- Use CyberDuck to SFTP into your account on the
- On the server, navigate to the
- Download the
lab05folder to your Desktop (drag and drop it from the CyberDuck window)
- Open Thonny and view the relevant
Table of Contents
- Lab 5 Home
- Part 0: Warm-up with loops
- Part 1: For Loop practice
- Part 2: Strings and Loops
- OPTIONAL Part 3: Loops and graphics
- Ref: Disable Tests
- What is a loop variable, and how does it get its values?
Show AnswerA loop variable is the variable created when you create a loop, so if you write
for x in 'abc':,
xis 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
- What happens when you use
returninside a loop, and why might you want to do that?
Show AnswerAs always, if you use
returninside 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).