Today's lab will focus on looping through files and mapping data.
Software tools needed: web browser and Python IDLE programming
environment.
We will use two new turtle commands in this lab:
tortuga.stamp()
tortuga.goto(10,30)would send the turtle, named tortuga to the point (10,30).
For example, we can add a stamp() command to our loop that draws a hexagon:
We can also use the goto command to move our turtle directly to a location:
We can add a background image to our turtle programs using the bgpic() command for screens. For example, both challenges below have a background image:
When you have a lot of data, it's easier to store it in a file, then to type it all in. Lines of a file are stored as strings (sequences of characters), but we often want to use numbers. This next part of the lab focuses on extracting numbers from strings. Here's our goal:
Write a program that prompts the user to enter a list of numbers. Each number is separated from the next by a comma (','). Your program should then print out the numbers, one per line. Here is a sample interaction:
Please enter your list of numbers: 3, 1, 4, 5, 1, 9 You entered: 3 1 4 5 1 9 Thank you for using my program!
Let's start by breaking down the problem into a "To Do" list:
As we've done in past programs, let's fill in the steps:
nums = input('Please enter your list of numbers: ')
numList = nums.split(',')
print("You entered:\n") for n in numList: print(n)
print("Thank you for using my program!")
What if we had wanted to do something more with the numbers? For example, what if we wanted to total them and find out the average. Instead of printing the number in the loop, we would need to:
This template for programs is often called the accumulator design pattern, since a value (in this case, the total) accumulates in a variable.
Let's modify the program above to print out the total (this is very similar to the program written in lecture):
nums = input('Please enter your list of numbers: ')
numList = nums.split(',')
total = 0
print("You entered:\n") for n in numList: num = int(n) total = total + num
print("The total is", total)
Last time, we read strings from a file. We extract numerical data from a file by combining reading from a file with the type conversion functions int() (for whole numbers) and float() (for real numbers).
Here's the outline:
Here's an example of mapping points on the Lehman Campus:
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.