# HG changeset patch # User anoop # Date 1284728931 -19800 # Node ID b7c47307e5101d68ca4f74dd47920f1c72bfccad # Parent b459053192f1c6e08033255d0e67b986ba981a53 added dictionaries, getting started with for, other_type_of_plots and savefig. diff -r b459053192f1 -r b7c47307e510 dictionaries.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries.rst Fri Sep 17 18:38:51 2010 +0530 @@ -0,0 +1,177 @@ +.. 8.4 LO: dictionaries (2) +.. ------------------------ +.. * empty +.. * filled +.. * accessing via keys +.. * .values(), .keys() +.. * in +.. * iteration + +============ +Dictionaries +============ + +{{{ show the welcome slide }}} + +Welcome to the spoken tutorial on dictionaries. + +{{{ switch to next slide, outline slide }}} + +In this tutorial, we will see how to create empty dictionaries, learn +about keys and values of dictionaries. Checking for elements and +iterating over elements. + +{{{ switch to next slide on overview of dictionaries }}} + +A dictionary in general, is designed to look up meanings of +words. Similarly, Python dictionary is also designed to look up for a +specific key and retrieve the corresponding value. Dictionaries are +data structures that provide key-value mappings. Dictionaries are +similar to lists except that instead of the values having integer +indexes, dictionaries have keys or strings as indexes. + +Before we can proceed, start your IPython interpreter with the +``-pylab`` option. + +{{{ start ipython interpreter by issuing command ipython -pylab }}} + +Let us start by creating an empty dictionary, type the following in +your IPython interpreter. +:: + + mt_dict = {} + +Notice that unlike lists curly braces are used define ``dictionary``, + +{{{ move the mouse over curly braces to grab attention }}} + +Now let us see how to create a filled dictionary, +:: + + extensions = {'jpg' : 'JPEG Image', 'py' : 'Python script', 'html' : 'Html document', 'pdf' : 'Portable Document Format'} + +Notice that each key-value pair is separated by a comma + +{{{ move the mouse over the commas to grab attention }}} + +and each key and value are separated using a colon. + +{{{ move the mouse over the colon one by one to grab attention }}} + +Here, we defined four entries in the dictionary extensions. The keys +are + +{{{ spell the keys letter by letter }}} + +jpg, py, html, and pdf. + +Simply type, +:: + + extensions + +in the interpreter to see the content of the dictionary. Notice that +in dictionaries the order cannot be predicted and you can see that the +values are not in the order that we entered in. + +Like in lists, the elements in a dictionary can be accessed using the +index, here the index is the key. Try, +:: + + print extensions['jpg'] + +It printed JPEG Image. And now try, +:: + + print extensions['zip'] + +Well it gave us an error, saying that the key 'zip' is not in the +dictionary. + +Pause here for some time and try few more keys. Also try jpg in +capital letters. + +{{{ switch to next slide, adding and deleting keys and values in +dictionaries }}} + +Well that was about creating dictionaries, now how do we add or delete +items. We can add new items into dictionaries as, +:: + + extensions['cpp'] = 'C++ code' + +and delete items using the ``del`` keyword as, +:: + + del extension['pdf'] + +Let us check the content of the dictionary now, +:: + + extensions + +So the changes have been made. Now let us try one more thing, +:: + + extensions['cpp'] = 'C++ source code' + extensions + +As you can see, it did not add a new thing nor gave an error, but it +simply replaces the existing value with the new one. + +Now let us learn how to check if a particular key is present in the +dictionary. For that we can use ``in``, +:: + + 'py' in extensions + 'odt' in extensions + +So in short it will return ``True`` if the key is found in the +dictionary, and will return ``False`` if key is not present. Note that +we can check only for container-ship of keys in dictionaries and not +values. + +{{{ switch to next slide, Retrieve keys and values }}} + +Now let us see how to retrieve the keys and values. We can use the +method ``keys()`` for getting a list of the keys in a particular +dictionary and the method ``values()`` for getting a list of +values. Let us try them, +:: + + extensions.keys() + +It returned the ``list`` of keys in the dictionary extensions. And now +the other one, +:: + + extensions.values() + +It returned the ``list`` of values in the dictionary. + +{{{ switch to next slide, problem statement for the next solved +exercise }}} + +Now let us try to print the data in the dictionary. We can use ``for`` +loop to iterate. +:: + + for each in extensions.keys(): + print each, "-->", extensions[each] + + +{{{ switch to next slide, recap }}} + +This brings us to the end of this tutorial, we learned dictionaries +and saw how to create an empty dictionary, build a dictionary with +some data in it, adding data, ``keys()`` and ``values()`` methods, and +iterating over the dictionaries. + +{{{ switch to next slide, thank you slide }}} + +Thank you! + +.. Author: Anoop Jacob Thomas + Reviewer 1: + Reviewer 2: + External reviewer: diff -r b459053192f1 -r b7c47307e510 getting_started_with_for.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_for.rst Fri Sep 17 18:38:51 2010 +0530 @@ -0,0 +1,217 @@ +.. 3.2 LO: getting started with =for= (2) [anoop] +.. ----------------------------------------------- +.. * blocks in python +.. + (indentation) +.. * blocks in ipython +.. + ... prompt +.. + hitting enter +.. * =for= with a list +.. * =range= function + +============================= +Getting started with for loop +============================= + +{{{ show welcome slide }}} + +Hello and welcome to the tutorial getting started with ``for`` loop. + +{{{ switch to next slide, outline slide }}} + +In this tutorial we will see ``for`` loops in python, and also cover +the basics of indenting code in python. + +{{{ switch to next slide, about whitespaces }}} + +In Python whitespace is significant, and the blocks are visually +separated rather than using braces or any other mechanisms for +defining blocks. And by this method Python forces the programmers to +stick on to one way of writing or beautifying the code rather than +debating over where to place the braces. This way it produces uniform +code than obscure or unreadable code. + +A block may be defined by a suitable indentation level which can be +either be a tab or few spaces. And the best practice is to indent the +code using four spaces. + +Now let us move straight into ``for`` loop. + +{{{ switch to next slide, problem statement of exercise 1 }}} + +Write a for loop which iterates through a list of numbers and find the +square root of each number. Also make a new list with the square roots +and print it at the end. +:: + + numbers are 1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916 + +For the problem, first we need to create a ``list`` of numbers and +then iterate over the list and find the square root of each element in +it. And let us create a script, rather than typing it out in the +interpreter itself. Create a script called list_roots.py and type the +following. + +{{{ open the text editor and paste the following code there }}} +:: + + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] + square_roots = [] + for each in numbers: + sq_root = sqrt(each) + print "Square root of", each, "is", sq_root + square_roots.append(sq_root) + print + print square_roots + +{{{ save the script }}} + +Now save the script, and run it from your IPython interpreter. I +assume that you have started your IPython interpreter using ``-pylab`` +option. + +Run the script as, +:: + + %run -i list_roots.py + +{{{ run the script }}} + +So that was easy! We didn't have to find the length of the string nor +address of each element of the list one by one. All what we did was +iterate over the list element by element and then use the element for +calculation. Note that here we used three variables. One the variable +``numbers``, which is a list, another one ``each``, which is the +element of list under consideration in each cycle of the ``for`` loop, +and then a variable ``sq_root`` for storing the square root in each +cycle of the ``for`` loop. The variable names can be chosen by you. + +{{{ show the script which was created }}} + +Note that three lines after ``for`` statement, are indented using four +spaces. + +{{{ highlight the threee lines after for statement }}} + +It means that those three lines are part of the for loop. And it is +called a block of statements. And the seventh line or the immediate +line after the third line in the ``for`` loop is not indented, + +{{{ highlight the seventh line - the line just after for loop }}} + +it means that it is not part of the ``for`` loop and the lines after +that doesn't fall in the scope of the ``for`` loop. Thus each block is +separated by the indentation level. Thus marking the importance of +white-spaces in Python. + +{{{ switch to the slide which shows the problem statement of the first +problem to be tried out }}} + +Now a question for you to try, from the given numbers make a list of +perfect squares and a list of those which are not. The numbers are, +:: + + 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, 7056, 576, 2916 + +{{{ switch to next slide, problem statement of second problem in +solved exercie}}} + +Now let us try a simple one, to print the square root of numbers in +the list. And this time let us do it right in the IPython +interpreter. + +{{{ switch focus to the IPython interpreter }}} + +So let us start with making a list. Type the following +:: + + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] + for each in numbers: + +and now you will notice that, as soon as you press the return key +after for statement, the prompt changes to four dots and the cursor is +not right after the four dots but there are four spaces from the +dots. The four dots tell you that you are inside a block. Now type the +rest of the ``for`` loop, +:: + + sq_root = sqrt(each) + print "Square root of", each, "is", sq_root + +Now we have finished the statements in the block, and still the +interpreter is showing four dots, which means you are still inside the +block. To exit from the block press return key or the enter key twice +without entering anything else. It printed the square root of each +number in the list, and that is executed in a ``for`` loop. + +Now, let us generate the multiplication table of 10 from one to +ten. But this time let us try it in the vanilla version of Python +interpreter. + +Start the vanilla version of Python interpreter by issuing the command +``python`` in your terminal. + +{{{ open the python interpreter in the terminal using the command +python to start the vanilla Python interpreter }}} + +Start with, +:: + + for i in range(1,11): + +and press enter once, and we will see that this time it shows four +dots, but the cursor is close to the dots, so we have to intend the +block. So enter four spaces there and then type the following +:: + + + print "10 *",i,"=",i*10 + +Now when we hit enter, we still see the four dots, to get out of the +block type enter once. + +Okay! so the main thing here we learned is how to use Python +interpreter and IPython interpreter to specify blocks. But while we +were generating the multiplication table we used something new, +``range()`` function. ``range()`` is an inbuilt function in Python +which can be used to generate a ``list`` of integers from a starting +range to an ending range. Note that the ending number that you specify +will not be included in the ``list``. + +Now, let us print all the odd numbers from 1 to 50. Let us do it in +our IPython interpreter for ease of use. + +{{{ switch focus to ipython interpreter }}} + +{{{ switch to next slide, problem statement of the next problem in +solved exercises }}} + +Print the list of odd numbers from 1 to 50. It will be better if +you can try it out yourself. + +It is a very trivial problem and can be solved as, +:: + + print range(1,51,2) + +This time we passed three parameters to ``range()`` function unlike +the previous case where we passed only two parameters. The first two +parameters are the same in both the cases. The first parameter is the +starting number of the sequence and the second parameter is the end of +the range. Note that the sequence doesn't include the ending +number. The third parameter is for stepping through the sequence. Here +we gave two which means we are skipping every alternate element. + +{{{ switch to next slide, recap slide }}} + +Thus we come to the end of this tutorial. We learned about blocks in +Python, indentation, blocks in IPython, for loop, iterating over a +list and then the ``range()`` function. + +{{{ switch to next slide, thank you slide }}} + +Thank you! + +.. Author: Anoop Jacob Thomas + Reviewer 1: + Reviewer 2: + External reviewer: diff -r b459053192f1 -r b7c47307e510 other_type_of_plots.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other_type_of_plots.rst Fri Sep 17 18:38:51 2010 +0530 @@ -0,0 +1,220 @@ +.. 2.4 LO: other types of plots (3) [anoop] +.. ----------------------------------------- +.. * scatter +.. * pie chart +.. * bar chart +.. * log +.. * illustration of other plots, matplotlib help + +=================== +Other type of plots +=================== + +{{{ show the first slide }}} + +Hello and welcome to the tutorial other type of plots. + +{{{ show the outline slide }}} + +In this tutorial we will cover scatter plot, pie chart, bar chart and +log plot. We will also see few other plots and also introduce you to +the matplotlib help. + + +Let us start with scatter plot. + +{{{ switch to the next slide }}} + +In a scatter plot, the data is displayed as a collection of points, +each having the value of one variable determining the position on the +horizontal axis and the value of the other variable determining the +position on the vertical axis. This kind of plot is also called a +scatter chart, scatter diagram and scatter graph. + +Before we proceed further get your IPython interpreter running with +the ``-pylab`` option. Start your IPython interpreter as +:: + + ipython -pylab + +{{{ open the ipython interpreter in the terminal using the command +ipython -pylab }}} + +{{{ switch to the next slide having the problem statement of first +exercise }}} + +Now, let us plot a scatter plot showing the percentage profit of company A +from the year 2000-2010. The data for the same is available in the +file ``company-a-data.txt``. + +{{{ open the file company-a-data.txt and show the content }}} + +The data file has two lines with a set of values in each line, the +first line representing years and the second line representing the +profit percentages. + +{{{ close the file and switch to the terminal }}} + +To product the scatter plot first we need to load the data from the +file using ``loadtxt``. We learned in one of the previous sessions, +and it can be done as :: + + year,profit = loadtxt('/home/fossee/other-plot/company-a-data.txt',dtype=type(int())) + +Now in-order to generate the scatter graph we will use the function +``scatter()`` +:: + + scatter(year,profit) + +Notice that we passed two arguments to ``scatter()`` function, first +one the values in x-coordinate, year, and the other the values in +y-coordinate, the profit percentage. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try out, plot the same data with red +diamonds. + +**Clue** - *try scatter? in your ipython interpreter* + +.. scatter(year,profit,color='r',marker='d') + +Now let us move on to pie chart. + +{{{ switch to the slide which says about pie chart }}} + +A pie chart or a circle graph is a circular chart divided into +sectors, illustrating proportion. + +{{{ switch to the slide showing the problem statement of second +exercise question }}} + +Plot a pie chart representing the profit percentage of company A, with +the same data from file ``company-a-data.txt``. So let us reuse the +data we have loaded from the file previously. + +We can plot the pie chart using the function ``pie()``. +:: + + pie(profit,labels=year) + +Notice that we passed two arguments to the function ``pie()``. The +first one the values and the next one the set of labels to be used in +the pie chart. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try out, plot a pie chart with the +same data with colors for each wedges as white, red, black, magenta, +yellow, blue, green, cyan, yellow, magenta and blue respectively. + +**Clue** - *try pie? in your ipython interpreter* + +.. pie(t,labels=s,colors=('w','r','k','m','y','b','g','c','y','m','b')) + +{{{ switch to the slide which says about bar chart }}} + +Now let us move on to bar chart. A bar chart or bar graph is a chart +with rectangular bars with lengths proportional to the values that +they represent. + +{{{ switch to the slide showing the problem statement of third +exercise question }}} + +Plot a bar chart representing the profit percentage of company A, with +the same data from file ``company-a-data.txt``. + +So let us reuse the data we have loaded from the file previously. + +We can plot the bar chart using the function ``bar()``. +:: + + bar(year,profit) + +Note that the function ``bar()`` needs at least two arguments one the +values in x-coordinate and the other values in y-coordinate which is +used to determine the height of the bars. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try, plot a bar chart which is not +filled and which is hatched with 45\ :sup:`o` slanting lines as shown +in the image in the slide. + +**Clue** - *try bar? in your ipython interpreter* + +.. bar(year,profit,fill=False,hatch='/') + +{{{ switch to the slide which says about bar chart }}} + +Now let us move on to log-log plot. A log-log graph or log-log plot is +a two-dimensional graph of numerical data that uses logarithmic scales +on both the horizontal and vertical axes. Because of the nonlinear +scaling of the axes, a function of the form y = ax\ :sup:`b` will +appear as a straight line on a log-log graph + +{{{ switch to the slide showing the problem statement of fourth +exercise question }}} + + +Plot a `log-log` chart of y=5*x\ :sup:`3` for x from 1-20. + +Before we actually plot let us calculate the points needed for +that. And it could be done as, +:: + + x = linspace(1,20,100) + y = 5*x**3 + +Now we can plot the log-log chart using ``loglog()`` function, +:: + + loglog(x,y) + +To understand the difference between a normal ``plot`` and a ``log-log +plot`` let us create another plot using the function ``plot``. +:: + + figure(2) + plot(x,y) + +{{{ show both the plots side by side }}} + +So that was ``log-log() plot``. + +{{{ switch to the next slide which says: "How to get help on +matplotlib online"}}} + +Now we will see few more plots and also see how to access help of +matplotlib over the internet. + +Help about matplotlib can be obtained from +matplotlib.sourceforge.net/contents.html + +.. #[[Anoop: I am not so sure how to do the rest of it, so I guess we + can just browse through the side and tell them few. What is your + opinion??]] + +Now let us see few plots from +matplotlib.sourceforge.net/users/screenshots.html + +{{{ browse through the site quickly }}} + +{{{ switch to recap slide }}} + +Now we have come to the end of this tutorial. We have covered scatter +plot, pie chart, bar chart, log-log plot and also saw few other plots +and covered how to access the matplotlib online help. + +{{{ switch to the thank you slide }}} + +Thank you! + +.. Author: Anoop Jacob Thomas + Reviewer 1: + Reviewer 2: + External reviewer: diff -r b459053192f1 -r b7c47307e510 savefig.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig.rst Fri Sep 17 18:38:51 2010 +0530 @@ -0,0 +1,111 @@ +======= +Savefig +======= + +Hello and welcome to the tutorial. In this tutorial you will learn how +to save plots using Python. + +Start your IPython interpreter with the command :: + + ipython -pylab + +It will start your IPython interpreter with the required python +modules for plotting and saving your plots. + +{{{ Open ipython }}} + +Now let us plot something, let us plot a sine wave from minus 3 pi to +3 pi. Let us start by calculating the required points for the plot. It +can be done using linspace as, :: + + x = linspace(-3*pi,3*pi,100) + +We have stored required points in x. Now let us plot the points using +the statement :: + + plot(x,sin(x)) + +{{{ Keep the plot open }}} + +Done! we have made a very basic sine plot, now let us see how to save +the plot for future use so that you can embed the plot in your +reports. + +{{{ Switch the focus to IPython interpreter window }}} + +For saving the plot, we will use savefig function, and it has to be +done with the plot window open. The statement is, :: + + savefig('/home/fossee/sine.png') + +Notice that ``savefig`` function takes one argument which is a string +which is the filename. The last 3 characters after the ``.`` in the +filename is the extension or type of the file which determines the +format in which you want to save. + +{{{ Highlight the /home/fossee part using mouse movements }}} + +Also, note that we gave the full path or the absolute path to which we +want to save the file. + +{{{ Highlight the .png part using mouse movements }}} + +Here I have used an extension ``.png`` which means i want to save the +image as a PNG file. + +Now let us locate ``sine.png`` file saved. We saved the file to +``/home/fossee`` so let us navigate to ``/home/fossee`` using the +file browser. + +{{{ Open the browser, navigate to /home/fossee and highlight the file +sine.png }}} + +Yes, the file ``sine.png`` is here and let us check the it. + +{{{ Open the file sine.png and show it for two-three seconds and then +close it and return to IPython interpreter, make sure the plot window +is still open, also don't close the file browser window }}} + +So in-order to save a plot, we use ``savefig`` function. ``savefig`` +can save the plot in many formats, such as pdf - portable document +format, ps - post script, eps - encapsulated post script, svg - +scalable vector graphics, png - portable network graphics which +support transparency etc. + +#[slide must give the extensions for the files - Anoop] + +Let us now try to save the plot in eps format. ``eps`` stands for +encapsulated post script, and it can be embedded in your latex +documents. + +{{{ Switch focus to the already open plot window }}} + +We still have the old sine plot with us, and now let us save the plot +as ``sine.eps``. + +{{{ Switch focus to IPython interpreter }}} + +Now, We will save the plot using the function ``savefig`` :: + + savefig('/home/fossee/sine.eps') + +{{{ Switch focus to file browser window }}} + +Now let us go to ``/home/fossee`` and see the new file created. + +{{{ Highlight the file sine.eps with a single mouse click for 2 +seconds and then double click and open the file }}} + +Yes! the new file ``sine.eps`` is here. + +Now you may try saving the same in pdf, ps, svg formats. + +Let us review what we have learned in this session! We have learned to +save plots in different formats using the function ``savefig()``. + +Thank you! + +.. Author: Anoop Jacob Thomas + Reviewer 1: + Reviewer 2: + External reviewer: