{ "cells": [ { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "from __future__ import print_function\n", "import matplotlib\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## PH2150- Scientific Computing and Employabilty\n", "### Introduction to Python (1 week) Lecture 2\n", "### Dr. Andrew Casey (a.casey@rhul.ac.uk, W054)\n", "\n", "## Review of post Exam Topics\n", "\n", "* Python Environment\n", "* Variable Types\n", "* Modules, Packages, Libraries\n", "* Control Structures\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## The *Python* Environment\n", "\n", "The teaching laboratory computers are all 64-bit Windows 10 machines, although *Python* is cross platform we prefer you to use these machines as (at least my expertise lies with Windows rather than Apple IoS). However feel free to use your own laptop/operating system but the support may not be so great for Mac users.\n", "\n", "### Python 2.x versus Python 3.x\n", "\n", "\n", "There are two variants of *Python*, if you learn one you will be able to easily use the other with some small changes in syntax. This year we have chosen to use *Python* 3.6.\n", "\n", "The environment installed in the teaching lab is called *Anaconda* and can be downloaded here:\n", "* https://www.anaconda.com/download/\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Launch Anaconda Navigator from the start menu\n", "Within the navigator we will use *Jupyter* (for notebooks like this one) and *Spyder* (Scientific PYthon Development EnviRonment) for editing code and running code from the interpreter.\n", "\n", "On these machines you can run *Python* 2.x or 3.x, in the Navigator (within the environments tab select *Python36* for 3.x or *Base* for 2.x) we have added a **PH2150** environment for this course which is a *Python* 3.x environment compatible with a 3D package called *mayavi*.\n", "\n", "The Environments tab indexes (and allows you to update) the packages that are available within the selected Environment.\n", "\n", "In addition commands can be run directly from a command line prompt using the *Anaconda Prompt* from the start menu, or by opening a terminal from the environment tab (clicking on the play symbol after the environment name)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Spyder (Scientific PYthon Developement EnviRonment)\n", "\n", "\n", "We will open this to take a quick look at some of the features:\n", "\n", "* If you have selected the correct environment then it should say *Python* 3.x in the interpreter\n", "* The working directory (where you store and run the code from) can be modified using the GUI.\n", "* There are many options that can be set about how the environment performs, for example initially the graphical output of code i.e. a matplotlib plot may be set to appear *inline* in the interpreter. It is more flexible for this to open in it's own window (allowing zooming, saving as pdf etc) to this you need to update the prefrences for how the graphics are displayed.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "> Select Tools ->\n", ">> Preferences - opens a dialog box\n", ">> Within Prefrences select IPython Console (this controls the settings of the interpreter)\n", ">>> Select the graphics tab - Change graphics backend from *inline* to *Automatic* or *QT5*" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Variables in computing.\n", "\n", "A variable in computer programming is a storage location associated with a symbolic name that contains a known or unknown value. In Python the variable is assigned a value by using the = symbol. \n", "### = is the assignment operator\n", "\n", "Variables come in many types, and the way that your code interacts with the variable dependends on the data type.\n", "The following are common variables types that we will encounter:\n", "\n", "* Numbers\n", "* Strings\n", "* List\n", "* Tuple\n", "* Dictionary\n", "* Boolean\n", "* Object\n", "* None ( A special variable type, that means non existent, not known or empty)\n", "* Array \n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Variable Names\n", "Variable names in *Python* can contain alphanumerical characters a-z, A-Z, 0-9 and some special characters such as _.\n", "Normal variable names must start with a letter. By convention, variable names start with a lower-case letter.\n", "### *Python* keywords that cannot be used as variable names:\n", "\n", "\n", " and, as, assert, break, class, continue, def, del, elif, else, except, \n", " exec, finally, for, from, global, if, import, in, is, lambda, not, or,\n", " pass, print, raise, return, try, while, with, yield\n", "\n", "**Note:** Be aware of the keyword `lambda`, which could easily be a natural choice of variable name in a scientific program. But being a keyword, it cannot be used as a variable name.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Numbers in *Python*\n", "\n", "*Python* has four basic numerical types.\n", "\n", "* Floating point numbers (floats)\n", "* Integers (less than 32-bit), and Long Integer (greater than 32-bit)\n", "* Complex numbers" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value= 4 \n" ] }, { "data": { "text/plain": [ "int" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x=4 # assigns the value '4' to the variable 'x'\n", "print('value=',x,type(x)) # print the string \"value=\", x and identify varaible type\n", "type(x)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value= (4+2j) \n", "4.0 2.0\n" ] } ], "source": [ "xx=4+2j\n", "print('value=',xx,type (xx))\n", "print(xx.real, xx.imag)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value= 4.0\n", "['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']\n" ] } ], "source": [ "yy=4.0\n", "print('value=',yy)\n", "type(yy)\n", "print(dir(yy))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Variable type *string*\n", "\n", "A string is the variable type that stores characters, i.e. stores text.\n", "\n", "The string is created by inserting the characters that make up the string between '*insert text here*'" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AndrewAndrewAndrewAndrew\n", "r\n", "And\n", "ANDREW\n" ] } ], "source": [ "mystring='Andrew' # using '' creates the string\n", "type(mystring)\n", "print(4*mystring) # What happens when you combine strings with operators\n", "print(mystring[3]) # you can index individual characters from a string\n", "print (mystring[0:3]) # you can slice elements out of a string\n", "print(mystring.upper()) # there are many functions that operate on strings e.g. upper changes all to uppercase" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Variable type *list*\n", "\n", "A list is a flexible variable type that can store a list of variables (which can have mixed types) within in it. E.g. a list of numbers, a list of names, or a combination of numbers, strings and even other lists.\n", "\n", "The list is created using the syntax mylist = [element1, element2,..., last element]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4.0, 'Andrew']\n", "\n", "5\n", "1\n", "['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']\n" ] } ], "source": [ "mylist=[1,2,3,4.0,'Andrew']\n", "print(mylist)\n", "print(type (mylist))\n", "print(len(mylist)) # returns the number of elements in the list\n", "print(mylist[0]) # index [0] returns the first element in the list \n", "print(dir(mylist))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Modules, packages\n", "\n", "Most of the functionality in *Python* is provided by modules. The *Python* Standard Library is a large collection of modules that provides cross-platform implementations of common facilities such as access to the operating system, file I/O, string management, network communication, and much more.\n", "\n", "**A Module:** A file containing *Python* definitions (functions, variables and objects) themed around a specific task. The module can be imported into your program. \n", "\n", "To use a module in a *Python* program it first has to be imported. A module can be imported using the import statement. The convention is that all import statements are made at the beginning of your code. For example, to import the module *math*, which contains many standard mathematical functions, we can do:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']\n" ] } ], "source": [ "import math # import the module called math\n", "print(dir(math)) #returns all the names of functions avaialble within the math module" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.6457513110645907\n" ] } ], "source": [ "#After importing these functions are now available\n", "x=math.sqrt(7) # syntax for assigning a value of the square root (function from math) of 7 to the varaible x\n", "print(x)\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function sqrt in module math:\n", "\n", "sqrt(x, /)\n", " Return the square root of x.\n", "\n", "None\n" ] } ], "source": [ "print(help(math.sqrt))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Different ways to import modules and functions\n", "### import modulename e.g. import math\n", "then you can use function by calling modulename.functionname()\n", "### from modulename import functionname e.g. from math import sqrt\n", "Explicitly import a function by its name also you to call the functionname()\n", "### from modulename import*\n", "imports all the functionnames from the module\n", "### import modulename as alias\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "
" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "x=np.array([1,2,3,4])\n", "y=np.sin(x)\n", "plt.plot(x,y)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Modules, packages\n", "A Package: Is a set of modules or a directory containing modules linked through a shared theme. Importing a package does not automatically import all the modules contained within it. \n", "\n", "## Some useful packages:\n", "* *SciPy* (maths, science and enginering module),\n", "* *Numpy* (Numerical Python for arrays, fourier transforms and more),\n", "* *matplotlib* (graphical representation), \n", "* *pandas* (datareader)\n", "* *mayavi* (3D visualisation module in Enthought distribution)\n", "\n", "If when running your script you get the error:\n", "\n", "**ImportError:** No module named [module/package name]\n", "\n", "Then you may need to install the package into your environment using the Anaconda Navigator Environment tab" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Control Structures (*if, for, while, else, elif*)\n", "\n", "In general, statements are executed sequentially, top to bottom.\n", "There are many instances when you want to break away from this e.g,\n", "\n", "* **Branch point**: choose to go in one direction or another based on meeting some condition.\n", "* **Repeat:** You may want to execute a block of code several times.\n", "\n", "Programming languages provide various control structures that allow for more complicated execution paths.\n", "Here we will use conditionals and loops:\n", "\n", "* **if**\n", "* **while**\n", "* **for** \n", "* **else**\n", "* **elif**\n", "\n", "In addition the following functions are useful for control structures,\n", "* **range**\n", "* **break**\n", "* **continue**\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Control Structures: Boolean Variable type (True of False).\n", "\n", "**Variable type** – *Boolean* (True or False)\n", "\n", "\n", "* $==$ is the equivalent to operator. Returns true if both operands are the same.\n", "\n", "* $!=$ is not equal to operator. True if both the operands are not equal else False.\n", "\n", "* $>$ is greater than operator. True if the first operand is greater than the second operand.\n", "* $>=$ is greater than or equal to operator. True if the first operand is greater than or equal to the second operand.\n", "\n", "Similarly, $<$ and $<=$ are less than and less than or equal to operators.\n", "\n", "Combined with the logical operators *and, or, not* allows more complex conditional statements.\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "x=2\n", "print(x==3) # Is x equivalent to 3?\n", "print(x>=1 and x<3) # combination of operators" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## The *if* statement\n", "\n", "The *if* statement is used to check a condition: if the condition is TRUE, we run a block of statements (the if-block), else (FALSE) we process another block of statements (else-block) or continue if no optional else clause.\n", "\n", "**if** guess == number: # 1st condition \n", "\n", " # the if block if condition is TRUE (note indented)\n", " \n", "**else:** \n", " \n", " # the else block if condition is FALSE (note indented)\n", " \n", "After running either block of statements you drop back into the main programme.\n", "\n", "The *elif* statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE..\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## The *if* statement\n", "![title](images\\if_else.jpg)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## The *elif* statement\n", "![title](images\\elif.jpg)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## *if* example" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5]\n", "4\n", "length of x = 5\n" ] } ], "source": [ "x=[1,2,3,4,5]\n", "if len(x)<10: # if this condition is true run the idented block of statements\n", " print(x) # block of statements\n", " print(x[3])\n", " print('length of x =',len(x)) # when you reach the end of the block the if statement is finsished" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## The *for* loop\n", "\n", "Loops: *for* loops are traditionally used when you have a piece of code which you want to repeat a number of times. As an alternative, there is the *while* Loop, the *while* loop is used when a condition is to be met, or if you want a piece of code to repeat until intrupted by another event.\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Current Letter : P\n", "Current Letter : y\n", "Current Letter : t\n", "Current Letter : h\n", "Current Letter : o\n", "Current Letter : n\n", "Current fruit : banana\n", "Current fruit : apple\n", "Current fruit : mango\n", "Current fruit : banana\n", "Current fruit : apple\n", "Current fruit : mango\n", "['apple']\n" ] } ], "source": [ "for letter in 'Python': # loops for each character in string\n", " print( 'Current Letter :', letter)\n", "\n", "fruits = ['banana', 'apple', 'mango']\n", "for fruit in fruits: # loops for each element in list\n", " print ('Current fruit :', fruit)\n", "\n", "for index in range(len(fruits)): # loops for each element in list\n", " print ('Current fruit :', fruits[index])\n", "\n", "FruitsA=[x for x in fruits if x[0]=='a'] # returns [‘apple’], this is known as list comprehension.\n", "\n", "print(FruitsA)\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## *for* flowchart\n", "\n", "![title](images\\for_loop.jpg)\n", "\n", "Iterating over all the values in a sequence" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## *for* flowchart\n", "\n", "![title](images\\fornext_loop.jpg)\n", "\n", "Incrementing a for loop from start to end." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number :4\n", "You entered: 4\n", "Enter a number :5\n", "You entered: 5\n", "Enter a number :Q\n", "You entered: Q\n", "Goodbye\n" ] } ], "source": [ "#while expression: #while TRUE execute block of statements\n", "# \n", "\n", "var = 1\n", "while var == 1 : # This constructs an infinite loop\n", " num = input(\"Enter a number :\")\n", " print( \"You entered: \", num)\n", "\n", " if num=='Q': # This gives a route out of loop\n", " print ('Goodbye')\n", " break # break will terminate the loop\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## *while* flowchart\n", "\n", "![title](images\\while_loop.jpg)\n", "\n", "Continue until condition is FALSE." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }