Download presentation
Presentation is loading. Please wait.
1
Module 5 Working with Data
Python Programming Module 5 Working with Data Python Programming, 2/e
2
Working with Data One of the big advantages of using Python instead of the Lego software is that it makes it much easier to work with data. In order to run science experiments using the EV3 sensors it would be helpful to be able to record values over time. Python provides a list structure to make this relatively easy. Python Programming, 2/e
3
Lists Lists are ordered sequences of items. For instance, a sequence of n numbers might be called S: S = s0, s1, s2, s3, …, sn-1 Specific values in the sequence are referenced using subscripts. By using numbers as subscripts, mathematicians can succinctly summarize computations over items in a sequence using subscript variables. Python Programming, 2/e
4
Lists A list or array is a sequence of items where the entire sequence is referred to by a single name (i.e. s) and individual items can be selected by indexing (i.e. s[i]). Python lists are dynamic. They can grow and shrink on demand. Python lists are also heterogeneous, a single list can hold different data types. Python Programming, 2/e
5
Creating Lists We can create a list by specifying its members inside square brackets. >>> my_list = [2, 3, 5, 7, 11, 13] >>> my_list [2, 3, 5, 7, 11, 13] Another way to create a list is to start with an empty list and then append new values. >>> new_list = [] >>> new_list.append(5) >>> new_list.append(4) >>> new_list [5, 4] Python Programming, 2/e
6
Accessing Entries We can access the entries in a list using indexing.
We specify the subscript of the entry we want. >>> my_list = [2, 3, 5, 7, 11, 13] >>> my_list[0] 2 >>> my_list[5] 13 Notice the indexing starts counting at 0. We can also assign new values to entries. >>> my_list[3] = 6 >>> my_list[2, 3, 5, 6, 11, 13] Python Programming, 2/e
7
List Operations The membership operation (in) can be used to see if a certain value appears anywhere in a sequence. >>> my_list = [1,2,3,4] >>> 3 in my_list True Another nice thing we can do is to determine the length of a list. >>> my_list = [1, 2, 3, 4, 5] >>> len(my_list) 5 Python Programming, 2/e
8
List Operations Python also provides a special kind of loop that runs through all the entries of a list. >>> my_list = [1, 2, 3, 4, 5] >>> sum = 0 >>> for x in my_list: sum = sum + x >>> sum 15 Just as with a while loop the body of the loop can contain more than one line and is indicated by using indentation. Python Programming, 2/e
9
List Operations Python has many operations that can be performed on lists. These are just a few. Operator Meaning <list>[] Indexing len(<list>) Length for <var> in <list>: Iteration <expr> in <list> Membership (Boolean) <list>.append(x) Add element x to end of list. Python Programming, 2/e
10
Activity Write a program that creates a list of the integers 0-10, uses a for loop to calculate the sum of these integers and finally prints out the result. Python Programming, 2/e
11
Range Sometimes we want a loop that will repeat a fix number of times.
We can use a for loop for this purpose. The range(x)(where x is an integer) produces a sequence from 0 to x-1 (it has x elements) that you can loop over. This loop will iterate 10 times: for x in range(10): <body> Python Programming, 2/e
12
Reading and Storing Temperatures
The following program is temp_record and is available on the Wikispaces site. It will take 10 readings from the temperature probe at 1 second intervals. The results are stored in a list. Finally the list is printed along with its mean and standard deviation. Python Programming, 2/e
13
Reading and Storing Temperatures
from time import sleep from ev3 import * from numpy import mean, std t_sensor = TemperatureSensor('in1') t_sensor.mode = 'TEMP-C' temps = [] for i in range(10): temps.append(t_sensor.value()) sleep(1) Python Programming, 2/e
14
Reading and Storing Temperatures
print('Temperatures:') for x in temps: print(x) print('Mean: ', mean(temps)) print('Standard Dev: ', std(temps)) The numpy library has a variety of math functions that you may find useful. We used the mean and standard deviation function in the example. Python Programming, 2/e
15
Reading and Storing Temperatures
This program names the Temperature Sensor and creates an empty list. Next we use a for loop that iterates 10 times to read in the temperatures at 1 second intervals. These values are appended to the list. Another for loop iterates over the list of temperatures, printing them out. Finally the mean and standard deviation are calculated and printed. Python Programming, 2/e
16
Activity Modify the program so that you calculate the mean directly instead of using the library function. Python Programming, 2/e
17
Sending Data to a File If we are generating a lot of data we may want to save it to a file so that we can analyze it later. First we need to open a file. outfile = open(‘data.txt’, ‘w’) The format is <filevar> = open(<name>, <mode>) Here <name> is the file name and mode is either ‘r’ for reading or ‘w’ for writing. Python Programming, 2/e
18
Writing to the File Writing to the file is just like writing to the screen, except you must specify the file to write to. outfile = open(‘data.txt’, ‘w’) print(‘Hello world!’, file=outfile) When you are done writing to the file you should close it. outfile.close() Python Programming, 2/e
19
Writing Temperature to a File
from time import sleep from ev3 import * t_sensor = TemperatureSensor('in1') t_sensor.mode = 'TEMP-C' outfile = open('data.txt', 'w') print(10, file=outfile) for i in range(10): print(t_sensor.value(), file=outfile) sleep(1) outfile.close() Python Programming, 2/e
20
Reading the File Once you have the file on you will probably want to read the data and perform some analysis. You open the the file for reading: infile = open('data.txt', 'r') At this point things get a little different. There are several methods we can use to read from the file. Python Programming, 2/e
21
File Methods <file>.read() – returns the entire remaining contents of the file as a single (possibly large, multi-line) string. <file>.readline() – returns the next line of the file. This is all text up to and including the newline character that marks the end of the line. <file>.readlines() – returns a list of the remaining lines in the file. Each list item is a single line including the newline characters. Python Programming, 2/e
22
File Processing Python views a file as a sequence of lines so we can loop through this sequence one line at a time. infile = open(‘data.txt’, ‘r’) for x in infile: # Line processing here # x will be the current line infile.close() Python Programming, 2/e
23
Activity Write a program that prints the integers 0-10 to a file.
Write another program that uses a for loop to read these integers one at a time and print them to the screen. Python Programming, 2/e
24
Graphing Data Once we have the data read into our program, we might want to graph it. There is a package called matplotlib that will allow us to do this. There are many nice graphical tools in this package, but we will just look at simple graphing. Python Programming, 2/e
25
Graphing Data Try the following to create a scatter plot:
>>> from pylab import plot, show >>> x = [0, 1, 2, 3, 4] >>> y = [0, 1, 4, 9, 16] >>> plot(x, y, ‘o’) This creates a graph but does not display it. It will print a cryptic message about the graph. To see it you need to type the following: >>> show() Python Programming, 2/e
26
Formatting Graph We can use different symbols for the points we are graphing. Options include ‘o’, ‘*’ , ‘x’, and ‘+’. You can also “connect the dots” using a command like: >>> plot(x, y, marker=‘o’) Finally you can graph the curve without any markers: >>> plot(x, y) Python Programming, 2/e
27
Graphing a Sequence You can also graph a single sequence of data.
The x coordinate will be the index values for the sequence. >>> x = [1, 0, 3, 2] >>> plot(x) >>> show() Python Programming, 2/e
28
Reading and Graphing The following program will read the temperatures and graph them. from pylab import plot, show infile = open('data.txt', 'r’) temperatures = [] for x in infile temperatures.append(float(x)) infile.close() plot(temperatures) show() Python Programming, 2/e
29
Activity Write a program that uses matplotlib to graph your favorite function. Examples might include y=x2, y=3x-2, y=sin(x), y=2x, etc. Python Programming, 2/e
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.