{ "metadata": { "name": "", "signature": "sha256:db55a54dd976f7a89d07074351a3d879b0056bbc3c5bb2777e5798bb643bebac" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Introduction to programming 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Clyde Fare and Jo\u00e3o Pedro Malhado, Imperial College London (contact: [python@imperial.ac.uk](mailto:python@imperial.ac.uk))\n", "\n", "This notebook is licensed under a [Creative Commons Attribution 4.0 (CC-by) license](http://creativecommons.org/licenses/by/4.0/)" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "The notebook: preleminaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This document is a [Jupyter notebook](http://jupyter.org) (previously known as IPython notebook). It is an interactive, multimedia document including in a single focument text, hypertext, mathematical equations, figures, but also computer code and the result of computations. If you want to see how it can be used in science an research, you can read about it in an [article in the journal Nature](http://dx.doi.org/10.1038/515151a) published in 2014." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notebooks are composed of *cells*, the two main cell types are code cells and [markdown](http://en.wikipedia.org/wiki/Markdown) cells\n", " \n", "* *Markdown cells* for non executable text, links, video clips images and other non code related material. (This text is in a markdown cell. Double click to see how it is written. You can press SHIFT+RETURN to make it look like before).\n", "\n", "* *Code cells* is where we write and execute python commands. Code cells show up like light grey rectangle with a label like *\"In[ ]\"*. You can see one below." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "New cells can be created by clicking the \"Insert Cell below\" icon with a '+' from the list icons at the top of the page.\n", "\n", "This will create a new cell immediately below the cell that is currently highlighted.\n", "\n", "By default new cells are code cells but you can change them by using the drop down menu to the immediate right of the icon list.\n", "\n", "You can move cells around using the up and down arrow icons. \n", "\n", "You can delete them by cutting them with the scissors icon - note at the moment you can't undo cutting a cell, so be careful! (What you can do is use the file menu and select \"Revert to checkpoint\" this will revert you to the previous saved state.)\n", "\n", "One of the nice things about markdown cells is that it can also display mathematics using a special syntax called [LaTeX](http://en.wikipedia.org/wiki/LaTeX). This allows us to produce nicely rendered equations, e.g. the Schr\u00f6dinger equation:\n", "\n", "$$i\\hbar\\frac{\\partial}{\\partial t} \\Psi = \\left ( -\\frac{\\hbar^2}{2\\mu}\\nabla^2 + V\\right ) \\Psi$$\n", "\n", "To include maths in a markdown cell we need to place it in between either single \\$ signs for equations in line with other text or double \\$\\$ signs for equations on their own line. \n", "\n", "Generate a new cell immediately below this text, change it to a markdown cell using the drop down menu and put the following text in it before pressing SHIFT+RETURN:\n", "\n", "\n", " Here's an equation: $$\\sin(\\frac{2\\pi}{3})=\\frac{\\sqrt{3}}{2}$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Below is a code cell with our first piece of code. To make the computer *execute* the code in the cell, we should put the cursor inside it and press SHIFT+RETURN" ] }, { "cell_type": "code", "collapsed": false, "input": [ "1+1" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The computer has executed the code and has reurned the result of our simple computation.\n", "\n", "Write some more complicated computation on the cell below (python on a notebook like thica can be an excelent calculator)." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Whe will not be exploring the plotting capabilities of the notebook in this course, but we can include all types of plots. If you execute the cell bellow (don't need to worry about what is written) you will get the plot of the function $f(x)=x^4-2 x^2$" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%pylab inline\n", "\n", "x=linspace(-2,2,50)\n", "y=x**4-2*x**2\n", "plot(x,y)\n", "ylim(-1,2)\n", "show()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What follows is a more complicated example. Execute the cell and move the slider." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from mpl_toolkits.mplot3d.axes3d import Axes3D\n", "from IPython.html.widgets import interact\n", "\n", "def mod_z_f(x, y, shift):\n", " r = (x**2 + y**2)**0.5\n", " return sin(r+shift)\n", "\n", "anim_x_data = linspace(-8,8,40)\n", "anim_y_data = linspace(-8,8,40)\n", "anim_mesh_data = meshgrid(anim_x_data, anim_y_data)\n", "anim_X_data = anim_mesh_data[0]\n", "anim_Y_data = anim_mesh_data[1]\n", "\n", "@interact(shift=[-4*pi,4*pi,pi/6])\n", "def flying_volcanoe(shift):\n", " anim_Z_data = mod_z_f(anim_X_data, anim_Y_data,shift)\n", " ax = gca(projection='3d')\n", " ax.plot_surface(anim_X_data, anim_Y_data, anim_Z_data, rstride=1, cstride=2, linewidth=.25, cmap=cm.coolwarm)\n", " show()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These examples are just to show the potential of the notebook. If you want to learn more about plotting with python you can have a look at another of the [Imperial College courses](https://github.com/imperialchem/python-data-viz-intro).\n", "\n", "The examples above are somewhat complicated, but do not worry, we will start with much simpler things. To do a clean start to what follows, go to the \"Kernel\" item on the top panel amd select \"Restart\"." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is an interactive tutorial! As you go through it any time you see something that looks like this:\n", "\n", " a = \"Hello\"\n", " \n", "that is followed by an empty code cell, you should type the expression in the code cell, press SHIFT+RETURN to execute it, and note the output.\n", "\n", "No copying and pasting! You'll learn the concepts better if you type them out yourself.\n", "\n", "Learning how to program is a skill that is developed by experimenting, trying ideas out, thinking about what works and what doesn\u2019t, and asking for help. **You are strongly encouraged to open new cells in the notebook and trying things out.** The computer will not complain!" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Overview" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this workshop we will distinguish different data types that can be manipulated in computer programs, and what kind of operations can be performed on each type. These will be the building blocks we will be using when constructing our programs. As these workshops develop we will see how to bring things together and construct functionality." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Data types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At the centre of all computer programs is manipulating and performing logical operations on data and data structures. Data structures can be very complex and abstract, but we'll start with simple data types which are present in almost all programming languages. We will first identify what they are, and look at what simple operations can be performed on them." ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Different types of numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In scientific computing, the most important data types are numbers. In a similar way to mathematics where we can distinguish different types of numbers (integers, rationals, reals, complex, etc...), in computing we also have different types of numbers.\n", "\n", "Is there a difference between 1 and 1.0?\n", "\n", "In order to enquire the data type of a given object we can use a function (more on what a function is later on) called *type* that tells you what kind of thing -- what data type -- something is. We can check for ourselves that Python considers '1' and '1.0' to be different data types:\n", "\n", " type(1)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ " type(1.0)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python is identifying the two numbers above as an *integer* and a *[floating point number](https://en.wikipedia.org/wiki/Floating_point)*. This difference is related to the way computers represent numbers, and can be important in some operation on some programming languages. Fortunately in Python (version 3 or above) we will not have to worry too much about them.\n", "\n", "What do you think the types of -1, 0.2, 9753 and 6.626e-34 are?\n", "\n", "Check your guesses in the cell below." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The last number of the sequence above is the Plank constant to 4 significant figures: 6.626×10-34. Therefore we see that we can use the *e* to specify scientific notation.\n", "\n", "What would be the result of\n", "\n", " 3e-3" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we change the sign\n", "\n", " 3e3" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is the type of *3e3*?\n", "\n", "Is it the same as the type of 300?" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The last numerical type available in Python is that of complex numbers. Python uses the convention followed in engineering, where the imaginary constant is represented by the letter *j*.\n", "\n", " type(1+2j)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What will the type of the difference of the complex number 1+2j and the pure imaginary number 2j be?" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Operations with numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The simplest programming operations you can do with numbers are the same as the ones you would do in a simple calculator. In fact you can use the notebook as a sophisticated calculator. Let's try a few.\n", "\n", " 1+1" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try a couple of expressions in the cell below. Note that you can use brackets to specify the order of the operations.\n", "\n", " (5+7)/2" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Calculate the energy of a photon of violet light with a wavelength of 440 nm (you can remind yourself of the value of the [constants you need](http://physics.nist.gov/cgi-bin/cuu/Category?view=html&Universal.x=70&Universal.y=18))." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Two \\* can be used for exponentiation. We can try it on a complex number.\n", "\n", " (3-1j)**2" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or to do a fourth root\n", "\n", " 16**(1/4)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One operation that we learn in primary school, seldom used in our daily lives, but is somewhat surprisingly useful in programming is the modulo operation which calculates the remainder of the division of two numbers. This is done uning the '%' symbol\n", "\n", " 3%2" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The mathematical operations available in de bare Python language are relativelly simple, and common functions like trigonometric functions, exponentials or logarithms are not available by default. These can be made available by loading special modules (to be discussed further later). By loading the [math module](https://docs.python.org/3/library/math.html), many more mathematical functions and constants are made available.\n", "\n", " import math\n", " math.sin(3*math.pi/2)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The math module is loaded when you use the pylab environment when doing the plots above. However, we shall not discuss these extensions further for the moment, as we want to focus on the main characteristics of the programming language." ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Strings of text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another very important data type we are interested in manipulating is text strings. This is evident when dealing with a text editor, a spell checker, or even how you are typing into this notebook, but even in simple computational tasks text strings will appear often.\n", "\n", "Text strings appear in quotations. If you type a simple\n", " \n", " Hello\n", "\n", "below, Python will not understand what you mean and output an error message" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you type it in quotes\n", "\n", " 'Hello'\n", "\n", "it will tolerate it much better" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And if you ask what type this quoted thing is, Python will inform you that it is a *string*\n", "\n", " type('Hello')" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the difference in type is related with the use of quotes and not the use of letters\n", "\n", " type(1.2)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ " type('1.2')" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "type(\"We can even make 1 single string with spaces, punctuation and numbers such as 0.00729\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that in the string above we used double quotes instead of single quotes. Both are indeed equivalent in Python, but we must be consistent.\n", "\n", "In the English language, because of the use of the apostrophe, single quotes can be problematic\n", "\n", " 'I woudn't want to contradict you'" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the example above, Python would think the string finishes half way through the second word, and it will not understand what the rest of the command means. The use of double quotes helps in this case.\n", "\n", " \"I woudn't want to contradict you\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or to use triple quotes ('''), which have the advantage of being used for long strings that do not fit in one line. You could put a full novel in triple quotes." ] }, { "cell_type": "code", "collapsed": false, "input": [ "'''This is a multiline string.\n", "With some horrible characters that would normally create complications: '{}\"/\n", "As you can see, it extends over more than one line'''" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Operations with strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We know what to expect from the operation *1+1* and we tested this operation above. We have also seen that *1* and *\"1\"* are essentially different objects, for a computer in general, and Python in this case. So let us see what the the following operation will result into\n", "\n", " \"1\"+\"1\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any ideas on what happened, or is the numeracy of the computer is broken beyond repair? It is certainly helpful to query what is the type of the result of the operation we just did.\n", "\n", " type(\"1\"+\"1\")" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Are things a bit more clear? What was achieved with the operation + acting on two strings (\"1\" and \"1\") was a string concatenation, i.e. we joined the two strings together. Let's try to do that again\n", "\n", " \"Hello \"+\"mate!\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We note here that there is no difference in the symbol we use for sumation +, and the symbol we use for string concatenation +. Yet the operations are essentially different, because the objects we are operating on are of different types. Summing (in a mathematical sense) two strings is an ill defined operation, and concatenating two numbers together would not be a very useful thing to do.\n", "\n", "Similarly, it is not defined the operation minus \"-\" between two strings\n", "\n", " \"Remove what?\" - \"what?\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's now try to outsmart the computer and \"add\" a string and a number\n", "\n", " 1+\"Hello\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us look at this error message (a traceback) in some detail.\n", "A traceback gives details on what was happening when Python encountered an Exception or Error -- something it doesn't know how to handle.\n", "\n", "There are many kinds of Python errors, with descriptive names to help us understand what went wrong. In this case we are getting a TypeError: we tried to do some operation on a data type that isn't supported for that data type.\n", "\n", "Python gives us a helpful error message as part of the TypeError:\n", "\n", " unsupported operand type(s) for +: 'int' and 'str'\n", " \n", "In order to render the operation meaningful we would need to convert the number into a string. This can be done using the *str()* function\n", "\n", " str(1)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can confirm that the type of the previous operation is a string. We can now meaningfully concatenate the two objects\n", "\n", " str(1)+\"Hello\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is important to understand what is going on. We are transforming the number 1 into the string \"1\" using the function *str()*, and concatenating the resulting string \"1\" with the second string \"Hello\" via the operation + between two strings.\n", "\n", "We can also be interested in the reverse operation, given a string we may want to use it as a number in order to perform some numerical operation. This can be done with the function *float()*, that converts a string into a floating point number.\n", "\n", " 37+float(\"2.998e8\")" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The hability to convert between data types is very useful and often occurs in solving practical problems.\n", "\n", "A second operation \\*, this time involving an integer number and a string.\n", "\n", " 20*\"pancake\"\n", " \n", "Before you try the command out, can you see that it would be strange if the result was a number?" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There you have, 20 pancakes for you.\n", "\n", "Note that the \\* operation in this case is between an integer and a string. You can see that\n", "\n", " \"20\"*\"pancake\"\n", "\n", "is not as good" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using a floating point (real) number will also not work\n", "\n", " 1.5*\"pancake\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the two operations with strings above, + and \\*, we can start to be creative and do some nice stuttering\n", "\n", " \"He\"+10*\"he\"+\"llo\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many operations that can be done with strings, and we will be looking at them as we go along, but one that often comes in handy is the *len()* function which gives the total number of characters (including spaces) in a string.\n", "\n", "We can use it to determine the number of characters in the stuttering word above\n", "\n", " len(\"He\"+10*\"he\"+\"llo\")" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write down the expression that would give you the difference in string length (character number) between the string above and a normal \"Hello\"." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Booleans" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want to introduce any logic in a program, or instruct the computer on how to perform instructions according to specific conditions, we need to make use of a less obvious but very important data type: the logical statements of *True* and *False*, called booleans\n", "\n", " type(True)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that they are capitalized\n", "\n", " type(true)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And are essentially different from a string with the word \"True\"\n", "\n", " type(\"True\")" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Booleans do not often show up explicitly written in programs. However they are present all the time as a result of some operation. For example a comparison of two numbers.\n", "\n", " -2 <= 1" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the expression above, the computer is testing whether -2 is smaller or equal to 1, and we should be happy to see that it got the order of the numbers right. The examples we use here are obvious, and we use them to illustrate how booleans work. In practice we will be dealing with more realistic cases.\n", "\n", "We can also test if two numbers are equal\n", "\n", " 5 == 5" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note the two = signs above. This is not a typo, == is used when we want to test for equality. We will see further down that one = sign has a different meaning.\n", "\n", "Similarly, we can test if two numbers are different\n", "\n", " 5 != 5" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Above we are testing if 5 is different from 5. Since they are equal, the result of the test is False.\n", "\n", "We can also compare two strings\n", "\n", " \"introvert\"==\"shy\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could also compare a string to a number, and we can expect these two things to be always different.\n", "\n", " \"1.0\"==1.0" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A common operation could be the comparison of the length of two strings\n", "\n", " len(\"introvert\") > len(\"shy\")" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us complicate things slightly. We can use the operation *not* to obtain the complementary of a boolean.\n", "\n", " not True" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If something is not True, then it is False! Note that what we wrote is not a string. It is the operation *not* on the boolean *True*.\n", "\n", "It should be easy to understand what the result of not False should be (create a new cell and test it, if it is not clear).\n", "\n", "Used on in these simple cases, the operation *not* does not seem very useful, but it can be used to negate increasingly more complex constructions\n", "\n", " not (3 > 6/2)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Can you see why we obtained this result?\n", "\n", "We can check the result of multiple logical operations together, using the logical operators *and* and *or*.\n", "\n", "If two expressions are joined by an *and*, they both have to be True for the overall expression to be True. \n", "\n", "If two expressions are joined by an *or*, as long as at least one is True, the overall expression is True.\n", "\n", "Let us give it a try\n", " \n", " 1 > 0 and 1 < 2" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although the use of brackets is not necessary, we can think of these compound conditional expressions as written as (1 > 0) and (1 < 2). Since each of the two expressions is True, the overall result is True.\n", "\n", "We can construct more complex logical statements\n", "\n", " (1 > 0 or 1 < 2) and 1 > 10" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Would the result be different if we change the position of the parenthesis?\n", "\n", " 1 > 0 or (1 < 2 and 1 > 10)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have now covered the three basic data types present in almost all programming languages: numbers (of several kinds), strings and booleans; as well as some simple operations specific to each type.\n", "\n", "Another language element common to all programming languages are variables. Variables allow us to store the result of specific operations for later use, making it easier to write programs. If, for example, we were writting a program to perform quantum mechanical calculations, it would be very tedious and error prone to explicitly write the Plank constant each time it is used. Instead we can store the value of the Plank constant into a variable.\n", "\n", " h=6.626e-34" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have just defined a variable \"called\" h, with the value 6.626e-34. Note that we used a single = sign in this process. One = is an assignement of the variable on the left hand side, the value on the right hand side; two == is a operation testing whether the left hand side is equal to the right hand side, and yields a boolean.\n", "\n", "When using a notebook interface, assigning a variable does not yield an output (see above). The output of a code cell is in general the output of the operation in that cell, so any cell that ends with a variable assignement will yield no output. This does not mean the operations in the cell have not been performed. Indeed we can see that the value of the Plank constant has been stored in variable h, by just executing the cell with the variable name\n", "\n", " h" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now use h in doing operations instead of typing the value explicitly\n", "\n", " h*400e12" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Defining a variable in programming is similar to defining a variable in mathematics, with some slight differences. We can define variables as numbers, but also as strings, booleans, or more complex structures.\n", "\n", " w=\"fantastic\"\n", " w" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ " type(w)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ " type(h)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In mathematics we define a variable and don't necessarily think of the specific values this variable takes. When we define a mathematical function $f(x)=x^2$, we often think of $x$ as a continuous \"thing\", taking all real values at the \"same time\". *In programming, variables always have one and only one well defined value at each point of the program.*\n", "\n", "The point just made about variable values at each point in the program illustrates well the notion that a program is a sequence of instructions. Let us define the following variables\n", "\n", " a=3\n", " b=4\n", " a=b\n", " b=\"done\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since in the above cell all instructions are variable assignements we don't see any output. But what is the value of each variable now? You can test them below. Any surprises?" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the examples above we have always used single letter names for variables. We are not restricted to this however, and although variable names can not have spaces or other special characters, it makes life easier for yourself and whoever reads your program, to use more explicit variable names.\n", "\n", " magic_number = 1/137\n", " amountOfFlour = 0.75\n", " my_name = \"Genghis\"" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again we see no output, but we are happy there are no error messages.\n", "\n", "In order to check the values of the variables all at once we can use the function *print()*, which simply prints its content on the screen.\n", "\n", " print(magic_number)\n", " print(amountOfFlour)\n", " print(my_name)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that unlike other cells, the code above does not have a \"Out \\[\\_\\]:\" tag associated with it on the left of the cell. This is because the *print()* function is not returning a result. The only thing that it does is printing to the screen, but otherwise has no other effect on the program.\n", "\n", "The *print()* function is suprisingly useful for a command that does so little. It is used to check values of variables without logically changing the code and thus is useful when checking for errors and debugging code. Never fear to use it!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = \"| (_| -()- -()- -()- -()- | -()- -()- -()- -()- ||\\n\"\n", "b = \"|_\\_|_/___|__|__|__|___|__|___|__|___________________________||\\n\"\n", "c = \"|________________________________|__|__()_|__()_|__()__|_____||\\n\"\n", "d = \" ___|)_______________________________________________________\\n\"\n", "e = \"|_/(|,\\____/_|___/_|____/_|______|___________________________||\\n\"\n", "f = \"|___/____________________________|___________________________||\\n\"\n", "g = \"| | | () | () | () | | ||\\n\"\n", "h = \"|__\\___|.________________________|___\\_|___\\_|___\\_|___|_____||\\n\"\n", "i = \"|__/|_______/|____/|_____/|______|___________________________||\\n\"\n", "j = \"|_____/__________________________|____\\|____\\|____\\|_________||\\n\"\n", "k = \"|____/___________________________|___________________________||\\n\"\n", "l = \"|__/___\\_._______________________|__|__|__|__|__|__|___|_____||\\n\"\n", "\n", "print(d + f + i + e + b + g + a + c + l + h + j + k)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Making decisions: if statements" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Life is made of decisions, and any minimally versatile code will need to execute different instructions depending on some criteria. An example from daily life would be: if it is hot, open the window; if it is not hot, don't open it! All programming languages provide mechanism to conditionally execute a piece of code. In python it takes the form:\n", "\n", " if 6 > 5:\n", " print(\"Six is greater than five!\")" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That was our first multi-line piece of code, and we need to pay attention to the indentation on the second line (the notebook tries to take care of this for you).\n", "Make sure to press space four times before typing the second line; Python needs them to understand what we want it to do. \n", "\n", "So what is going on here? When Python encounters the *if* keyword, it evaluates the expression following the keyword and before the colon (:). This expression must always evaluate to a boolean type, i.e. evaluate to True or evaluate to False.\n", "\n", "If that expression is True, Python executes the code in the indented code block under the *if* line. \n", "\n", "If that expression is False, Python skips over the code block.\n", "\n", " a=\"same\"\n", " if 0 > 1:\n", " a=\"changed\"\n", " a" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By using one *if* statement in the examples above, we have seen that how to execute code if the expression in the if statement is True, and if it is False no code is executed. A \"true choice\" will be executing one piece of code if the expression is True, and another piece of code if it is False. This is done using the *else* statement.\n", "\n", " sister_age = 15\n", " brother_age = 12\n", " if sister_age > brother_age:\n", " verdict=\"sister is older\"\n", " else:\n", " verdict=\"brother is older\"\n", " \n", " verdict" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An *else* is not stand alone and is always associated with a particular *if*.\n", "\n", "If we have more than two cases, we can use the *elif* keyword to check more cases. We can have as many *elif* cases as we want; Python will go down the code checking each *elif* until it finds a True condition or reaches the default *else* block.\n", "\n", " sister_age = 15\n", " brother_age = 12\n", " if sister_age > brother_age:\n", " verdict=\"sister is older\"\n", " elif sister_age == brother_age:\n", " verdict=\"sister and brother are the same age\"\n", " else:\n", " verdict=\"brother is older\"\n", " \n", " verdict" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You don't have to have an else block, if you don't need it. That just means there isn't default code to execute when none of the if or elif conditions are True:\n", "\n", " colour = \"orange\"\n", " if colour == \"green\" or colour == \"red\":\n", " print(\"Christmas colour!\")\n", " elif colour == \"black\" or colour == \"orange\":\n", " print(\"Halloween colour!\")\n", " elif colour == \"pink\":\n", " print(\"Valentine's Day colour!\")" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now go back to the cell above and change the first line to read\n", "\n", " colour = 'purple'\n", " \n", "Execute the cell again. Notice that, this time, nothing is printed." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us use an *if* statement to conditionally define the value of a variable. First define a variable *x* to have a real number value of your choice.\n", "Then build an *if* statement to define a variable *y* that should be the [absolute value](http://mathworld.wolfram.com/AbsoluteValue.html) of *x*. In this exercise we are aming at a general solution, i.e. one that would work for any value of *x*. Change the value of *x*, take positive and negative values, to check your solution works." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Summary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We covered the simplest data types found in most programming languages:\n", "\n", "* Numbers, further divided into integers, floating point numbers (floats) and complex numbers.\n", "* Strings, which are sequences of characters.\n", "* Booleans, True and False logical variables.\n", "\n", "Each of these data types has specific operations associated with them, and some operations which involve quantities of different types.\n", "\n", "Variables provide a way to call objects by a name. A variable can be of any type.\n", "\n", "The *if* statement provides a way to branch code execution: \"if *something* do this, otherwise do that\". It is a fundamental programming construct, and is present virtually in every program." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Exercises" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Menu specials" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Given a string *vegetable* and a string *entree*, create string \"Today our specials are: <vegetable> and <entree>\".\n", "Try it on the pairs:\n", "\n", "vegetable = 'asparagus' ; entree = 'pasta primavera'\n", "\n", "vegetable = 'artichoke' ; entree = 'steak frites'\n", "\n", "vegetable = 'kale' ; entree = 'fondue'" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Too long for twitter?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Twitter messages can not be more than 140 characters. Given a string *tweet*, print to screen the sentence \"Not for twits\" if the string is longer that 140 characters, and the word \"Soundbite\" if the string is less than or equal to 140 characters.\n", "Try it on:\n", "\n", "tweet='The Analytical Engine weaves algebraic patterns, just as the Jacquard loom weaves flowers and leaves. -- Ada Lovelace, the first programmer'\n", "\n", "tweet='Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.'" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Greatest out of 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define 3 variables *x*, *y* and *z* as three numbers of your choice. Write a piece of code that outputs the greatest of the three values. Change the values of *x*, *y* and *z* to check if your solution works." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }