Let’s Learn 6. Nested Loops Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus E-mail: ad@fivedots.coe.psu.ac.th 6. Nested Loops Loops inside loops
1. Draw a Line of Stars StarsLine.py A line of stars is one star printed again and again.
Draw a Block of Stars StarsBlock.py A loop that runs inside another loop is called a nested loop A block of stars is one star line printed again and again.
Draw Blocks of Stars StarsBlocks.py Two nested loops: blocks block line Blocks of stars are one star block printed again and again.
2. Star Steps StarSteps.py The range is 1 to numBlocks Steps of stars is one star line printed again and again, but with line length changing
Star Steps Showing the Variable StarStepsVar.py Star Steps Showing the Variable
3. Mult. Table for 5's MultTable.py The range is 1 to 10
Multi. Tables for 5, 6, 7 MultTables.py The range is 5 to 8 Multiplication Tables are one table printed again and again.
4. Drawing Many Shapes ShapeInput.py draws 1 shape using 1 loop:
If this loop was nested inside a numShapes loop, then many shapes could be printed. ShapesInput.py
A Different Offset So that we can see each shape, the outer numShapes loop moves the turtle using goto() this puts the turtle in a new position, but the turtle is still facing East A different offset would be to rotate the turtle before drawing a shape.
ShapesInput.py with Rotation
5. Hot Dog Combinations (combos) You can make a hot dog in lots of ways: with/without a sausage (dog) with/without bread (the bun) with/without tomato sauce (ketchup) with/without mustard with/without onion Some of these combos are silly. What are all the possible combos?
All the Combos: I always go for combo 29. What about you? What does combo 1 mean? How would you eat combo 7?
HotDogCombos.py Four nested loops
HotDogCombos2.py Prints the same as before, but the loops and ifs use False and True instead of 0 and 1
HotDog Calories What is the combo with the smallest number of calories? Combo 29 has 340 calories, which is high. Combo 1 is the best for a diet. What does it mean?
HotDogCalories.py I've switched back to loops using 0 and 1. Why?