Machine Learning
Reading Questions
Quiz
For Loops
- For loops allow you to do something repeatedly
- If you ever find yourself copying and pasting code it might be an indication that a for loop is appropriate.
For example the star program from the first lab
import turtle length = 100 angle = 144 turtle.forward(length) turtle.left(angle) turtle.forward(length) turtle.left(angle) turtle.forward(length) turtle.left(angle) turtle.forward(length) turtle.left(angle) turtle.forward(length) turtle.left(angle)
- Has two lines that are duplicated 5 times
This can be rewritten using a loop
import turtle length = 100 angle = 144 for i in [1, 2, 3, 4, 5]: turtle.forward(length) turtle.left(angle)
- Note, the code that is repeated is indented
Don’t forget the colon at the end of the
for
line
Range
- Writing in 1, 2, 3, 4, 5, gets annoying if you want a loop to run a lot of times
- Furthermore, if you want a loop to run some number of times based on user input, you don’t know how many numbers to put in the brackets
- The range function makes this possible
The looping star program
import turtle length = 100 angle = 144 for i in [1, 2, 3, 4, 5]: turtle.forward(length) turtle.left(angle)
Becomes
import turtle length = 100 angle = 144 for i in range(5): turtle.forward(length) turtle.left(angle)
The number in the parentheses is the number of times the loop will run