Today's lab will focus on loops and the random library in Python.
Software tools needed: web browser and Python IDLE programming environment.
Last lab, we wrote a program using Turtle graphics:
Click on the ► to run the program.
The range() function generates a sequence of numbers. For example, range(4) gives the sequence 0,1,2,3. While range(10) gives 0,1,2,3,4,5,6,7,8,9. In general, range(n) will give the sequence 0,1,2,...,n-1. We will discuss this more over the next couple of sections.
Work through 4.6 Iteration Simplifies our Turtle Program.
import turtle # set up alex wn = turtle.Screen() alex = turtle.Turtle() for aColor in ["yellow", "red", "purple", "blue"]: alex.color(aColor) alex.forward(50) alex.left(90) wn.exitonclick()
First, work through the textbook's section on the 4.7: The range Function.
Next, let's write a program that will print out:
10 9 8 7 6 5 4 3 2 1 Blast off!
If we were asked to print the numbers in the other direction, we could do this with the simplest range:
for i in range(11): print(i)followed by a print("Blast off!"). But we want to print out the numbers, 10, 9, 8, ... , 1. In the textbook section, they had a very useful command:
print(range(10, 0, -1))which printed [10, 9, 8, 7, 6, 5, 4, 3, 2, 1].
Let's use that with a for loop to print out our countdown:
for i in range(10,0,-1): print(i)
That gives all the pieces for our program! Now let's put them together and test it:
import randomThe random library includes a function that's similar to range, called randrange. As with range, you can specify the starting, stopping, and step values, and the function randrange chooses a number at random in that range. Some examples:
Notice that our turtle turns a degrees, where a is chosen at random between 0 and 359 degrees. What if your turtle was in a city and had to stay on a grid of streets (and not ramble through buildings)? How can you change the randrange() to choose only from the numbers: 0,90,180,270 (submit your answer as Problem #10).
If you finish the lab early, now is a great time to get a head start on the programming problems due early next week. There's instructors to help you and you already have Python up and running. The Programming Problem List has problem descriptions, suggested reading, and due dates next to each problem.