{ "cells": [ { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "## Scientific Computing - Lecture 2: Slicing, Conditionals, and Loops\n", "J.R. Gladden, University of Mississippi, Dept. of Physics Physics 730, Spring 2018" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "\n", "Conditionals are tests to see if some condition is True or False.\n", "In Python, the following are False: `False, 0, \"\", (), [], {}`\n", "and pretty much everyhting else is True\n", "These are called *Boolean* datatypes.\n", "\n", "To test two things, we can use these boolean operators: \n", "\n", "`==, <, >. <=, >=, !=,`\n", "\n", "`is, is not` (testing if two objects are the same object), `in` (tests if something is in a sequence)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1>0\n", "ilist=range(0,100,2)\n", "newlist=ilist\n", "2 in ilist\n", "312 in ilist\n", "newlist is ilist" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Else statements catch what happens if a test is False.\n", "This is how a user can input information into the program." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [], "source": [ "num=input('Enter a number: ')" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Conditional tests can be strung together. Note here that testing stops until something evaulates to True" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [], "source": [ "num=input('Enter a number: ')\n", "if num > 0 and num <= 1000: # another way to do this line is: 0 < num <= 1000:\n", " print 'The number is between 0 and 1000.'\n", "elif num < 0:\n", " print 'The number is negative.'\n", "#An additional test with 'elif'\n", "elif num > 0:\n", " print 'The number is positive.'\n", "else:\n", " print 'The number is zero.'\n" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Loops - for repetitive tasks\n", " \n", " Loops perform repetitive tasks. Common type are 'for' and 'while' loops.\n", "_range()_ - returns a list of integers, start at 0 is assumed. **Upper limit is NOT included!**" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "16\n", "36\n", "64\n" ] } ], "source": [ "alist=[2,4,6,8]\n", "\n", "for i in range(len(alist)):\n", " print alist[i]**2" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "**OR** this is a more 'pythonic' way to do it:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "4\n", "9\n", "16\n" ] } ], "source": [ "for i in alist: print i**2" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Au\n", "H\n", "He\n", "C\n", "Cu\n", "Pb\n" ] } ], "source": [ "elements=['Au', 'H', 'He','C','Cu','Pb']\n", "number=[79,1,2,6,29,82]\n", "\n", "for element in elements:\n", " print element" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### One can iterate over two lists in a parallel fashion using the `zip` function\n", "We are also using some _string formatting_ here." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The atomic number for Au is 79\n", "The atomic number for H is 1\n", "The atomic number for He is 2\n", "The atomic number for C is 6\n", "The atomic number for Cu is 29\n", "The atomic number for Pb is 82\n" ] } ], "source": [ "for element,number in zip(elements,number):\n", " print \"The atomic number for %s is %i\" % (element,number)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### While loops repeat as long as some condition is true and stops when it it false:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [], "source": [ "time=0\n", "y0=500.0\n", "y=y0\n", "while time <= 20 and y >= 0. :\n", " y=-9.8*time**2 + y0\n", " print 'At time = %g, the ball is located at %g m' % (time,y)\n", " time+=1" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "#### Might be useful to add a _break_ statement to automatically stop the loop if some condition is met.\n", "Here the condition is if the ball hit the ground ($y \\leq 0$)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "At time = 0,the ball is located at 500 m\n", "At time = 1,the ball is located at 490.2 m\n", "At time = 2,the ball is located at 460.8 m\n", "At time = 3,the ball is located at 411.8 m\n", "At time = 4,the ball is located at 343.2 m\n", "At time = 5,the ball is located at 255 m\n", "At time = 6,the ball is located at 147.2 m\n", "At time = 7,the ball is located at 19.8 m\n" ] } ], "source": [ "time=0.0\n", "y0=500.0\n", "y=y0\n", "while time <= 20:\n", " y=-9.8*time**2 + y0\n", " if y <= 0. : break\n", " print 'At time = %g,the ball is located at %g m' % (time,y)\n", " time+=1.0\n" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Sometimes it's useful to setup and infinite loop and break out when a condition is met!" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false, "deletable": true, "editable": true, "scrolled": true, "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Type an integer (0 to quit): 8\n", "You must type a number (integer or float)!\n", "The cube of 8 number is: 512\n", "Type an integer (0 to quit): 3\n", "You must type a number (integer or float)!\n", "The cube of 3 number is: 27\n", "Type an integer (0 to quit): 5\n", "You must type a number (integer or float)!\n", "The cube of 5 number is: 125\n", "Type an integer (0 to quit): 0\n", "Quitting this game...\n" ] } ], "source": [ "while 1:\n", " num=int(raw_input('Type an integer (0 to quit): '))\n", " if num ==0:\n", " print 'Quitting this game...' \n", " break\n", " if type(num) != type(1) or type(0.1):\n", " print \"You must type a number (integer or float)!\"\n", " print 'The cube of %g number is: %g' % (num,num**3)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true, "deletable": true, "editable": true }, "source": [ "## Functions\n", "### good way of making your code modular - easy to reuse parts of your code.\n", "\n", "First define the function, what parameters does it require? What does it return?" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": true, "deletable": true, "editable": true }, "outputs": [], "source": [ "def f(x,a,b):\n", " return b*x+a" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Now let's see how to use the function" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [], "source": [ "value=f(2,3,4)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "11" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "value" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "#### Optional Arguments\n", "Often convenient to give default values to certain parameters, but allow the option to change if needed." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.0\n", "7.0\n", "3.0\n" ] } ], "source": [ "def f2(x,a=1.,b=2.):\n", " return b*x+a\n", "print f2(2)\n", "print f2(2,a=3)\n", "print f2(2,b=1.)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "#### Variable number of arguments\n", "Sometimes convenient to call a function with a variable number of arguments. This is very flexible!!" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "14\n", "32\n" ] } ], "source": [ "def sumnums(*nums):\n", " sum=0\n", " for num in nums:\n", " sum+=num\n", " return sum\n", "\n", "print sumnums(2,3,4,5)\n", "print sumnums(4,2,7,8,9,2)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "#### Calling functions from other function\n", "This is also creates a lot of flexibility! Also note here the \"docstring\" in this example. This is the common way to document the way a function works. Note the the format I've used. " ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.5\n" ] } ], "source": [ "def myavg(*nums):\n", " '''\n", " Function to average a sequence of numbers.\n", " Usage: testavg = avg(70,80,75,99,98)\n", " Input: arbitrary length sequence of integers or floats\n", " Output: a float equal to the average\n", " History: version 0.1, last updated Jan. 23, 2012 by JRG\n", " '''\n", " #pass the sequence *nums just as it is, otherwise it sends a tuple object to sumnums\n", " sum=float(sumnums(*nums)) #convert to float to avoid division problems\n", " return sum/len(nums)\n", "\n", "print myavg(2,3,4,5)\n", "# You can access the docstring like this:\n", "myavg?" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Variable Scope\n", "Scope: where in the program a variable is known and what it's value is. This is very important to understand. Variables defined _inside_ a function is ONLY known inside the function - known as LOCAL scope. Variables defined at the \"root\" level are known everywhere (inside functions and outside) - this is known as GLOBAL scope." ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0\n", "6.0\n" ] }, { "ename": "NameError", "evalue": "name 'a' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtestscope\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0ma\u001b[0m \u001b[0;31m# Note this will return an error since 'a' only know inside the function.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'a' is not defined" ] } ], "source": [ "def testscope():\n", " a=1.\n", " b=2.\n", " c=3.\n", " print(a)\n", " return a+b+c\n", "\n", "print(testscope())\n", "\n", "print a # Note this will return an error since 'a' only know inside the function.\n" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "#### Global variables are accessible from within a function (test by commenting out the a=1 line), but variables within fucntions are only locally defined.\n", "\n", "However, changes made to mutable objects like lists are reflected outside the function\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 9, 16]\n" ] } ], "source": [ "def squareit(somenums):\n", " for i in range(len(somenums)):\n", " somenums[i]=somenums[i]**2\n", " return\n", "\n", "testlist=[1,2,3,4]\n", "squareit(testlist)\n", "print testlist # the original list is changed" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Excercise: Change 'squareit' to return a new list of the squares but leave the original list unchanged." ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4]\n", "[1, 4, 9, 16]\n" ] } ], "source": [ "def squareit2(somenums):\n", " sqrs=[]\n", " for num in somenums:\n", " sqrs.append(num**2)\n", " return sqrs\n", "\n", "testlist=[1,2,3,4]\n", "newlist=squareit2(testlist) \n", "print testlist \n", "print newlist" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "deletable": true, "editable": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.13" } }, "nbformat": 4, "nbformat_minor": 0 }