{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "ChEn-1070: Introduction to Chemical Engineering Spring 2019 UMass Lowell; Profs. Manohar and de Almeida **08Apr2019**\n", "\n", "# 05. Basic Flow Controls in Python\n", "$ \n", " \\newcommand{\\Amtrx}{\\boldsymbol{\\mathsf{A}}}\n", " \\newcommand{\\Bmtrx}{\\boldsymbol{\\mathsf{B}}}\n", " \\newcommand{\\Mmtrx}{\\boldsymbol{\\mathsf{M}}}\n", " \\newcommand{\\Imtrx}{\\boldsymbol{\\mathsf{I}}}\n", " \\newcommand{\\Pmtrx}{\\boldsymbol{\\mathsf{P}}}\n", " \\newcommand{\\Lmtrx}{\\boldsymbol{\\mathsf{L}}}\n", " \\newcommand{\\Umtrx}{\\boldsymbol{\\mathsf{U}}}\n", " \\newcommand{\\xvec}{\\boldsymbol{\\mathsf{x}}}\n", " \\newcommand{\\avec}{\\boldsymbol{\\mathsf{a}}}\n", " \\newcommand{\\bvec}{\\boldsymbol{\\mathsf{b}}}\n", " \\newcommand{\\cvec}{\\boldsymbol{\\mathsf{c}}}\n", " \\newcommand{\\rvec}{\\boldsymbol{\\mathsf{r}}}\n", " \\newcommand{\\norm}[1]{\\bigl\\lVert{#1}\\bigr\\rVert}\n", " \\DeclareMathOperator{\\rank}{rank}\n", "$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## Table of Contents\n", "* [Conditionals](#conditionals)\n", " + [If](#if)\n", "* [Loops](#loops)\n", " + [For](#for)\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditionals<a id=\"conditionals\"></a>\n", "Constructs that allow branching of operations. The most importants are:\n", " 1. `if` statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `If` statement<a id='if'></a>\n", "The general format is (*indentation observed*):\n", "```python\n", "if test1: # if test1 is a test statement\n", " statements1 # associated block\n", "elif test2: # optional elifs\n", " statements2\n", "elif test3: # more optional elifs etc.\n", " statements3\n", "else: # optional final else\n", " statements4\n", "```\n", "\n", "Test statements use logical operarors such as: \n", " + `==` tests for truth\n", " + `!=` tests for non-truth\n", " + `is` type\n", " + `is not` type\n", " + `in` inclusion\n", " + `or` or concatenation of test statements\n", " + `and` and concatenation of test statements" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "True\n", "False\n", "True\n", "False\n", "False\n", "True\n" ] } ], "source": [ "'''Logical operators'''\n", "\n", "a = [1,2,3]\n", "\n", "print( a == a )\n", "print( a != a )\n", "print( type(a) is list )\n", "print( type(a) is list() )\n", "print( 3 in a )\n", "print( a is None )\n", "print( a == a and type(a) is int )\n", "print( a[1] == a or type(a) is list )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example\n", "If-else example:\n", "```python\n", " if lithium is None: # test if element has type None \n", " try:\n", " import mendeleev # creates the `name` mendeleev\n", " except ImportError:\n", " print('Installing the \"mendeleev\" package...')\n", " print('')\n", " !pip install mendeleev\n", " import mendeleev\n", " \n", " lithium = mendeleev.element('Li')\n", " print('lithium data: ',[lithium])\n", " \n", " else: # final test\n", " print(lithium) # print all info on lithium\n", "```" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "lithium data: [Element(\n", "\tabundance_crust=20.0,\n", " \tabundance_sea=0.18,\n", " \tannotation='',\n", " \tatomic_number=3,\n", " \tatomic_radius=155.0,\n", " \tatomic_radius_rahm=220.00000000000003,\n", " \tatomic_volume=13.1,\n", " \tatomic_weight=6.94,\n", " \tatomic_weight_uncertainty=None,\n", " \tblock='s',\n", " \tboiling_point=1118.15,\n", " \tc6=1392.0,\n", " \tc6_gb=1410.0,\n", " \tcas='7439-93-2',\n", " \tcovalent_radius_bragg=150.0,\n", " \tcovalent_radius_cordero=128.0,\n", " \tcovalent_radius_pyykko=133.0,\n", " \tcovalent_radius_pyykko_double=124.0,\n", " \tcovalent_radius_pyykko_triple=None,\n", " \tcovalent_radius_slater=145.0,\n", " \tcpk_color='#b22222',\n", " \tdensity=0.534,\n", " \tdescription='Socket silvery metal. First member of group 1 of the periodic table. Lithium salts are used in psychomedicine.',\n", " \tdipole_polarizability=164.0,\n", " \tdiscoverers='Johann Arfwedson',\n", " \tdiscovery_location='Sweden',\n", " \tdiscovery_year=1817,\n", " \tec=<ElectronicConfiguration(conf=\"1s2 2s1\")>,\n", " \teconf='[He] 2s',\n", " \telectron_affinity=0.618049,\n", " \ten_allen=5.392,\n", " \ten_ghosh=0.105093,\n", " \ten_pauling=0.98,\n", " \tevaporation_heat=148.0,\n", " \tfusion_heat=2.89,\n", " \tgas_basicity=None,\n", " \tgeochemical_class='alkali metal',\n", " \tgoldschmidt_class='litophile',\n", " \tgroup=<Group(symbol=IA, name=Alkali metals)>,\n", " \tgroup_id=1,\n", " \theat_of_formation=159.3,\n", " \tionic_radii=[IonicRadius(\n", "\tatomic_number=3,\n", " \tcharge=1,\n", " \tcoordination='IV',\n", " \tcrystal_radius=73.0,\n", " \teconf='1s2',\n", " \tid=212,\n", " \tionic_radius=59.0,\n", " \tmost_reliable=True,\n", " \torigin='',\n", " \tspin='',\n", "), IonicRadius(\n", "\tatomic_number=3,\n", " \tcharge=1,\n", " \tcoordination='VI',\n", " \tcrystal_radius=90.0,\n", " \teconf='1s2',\n", " \tid=213,\n", " \tionic_radius=76.0,\n", " \tmost_reliable=True,\n", " \torigin='',\n", " \tspin='',\n", "), IonicRadius(\n", "\tatomic_number=3,\n", " \tcharge=1,\n", " \tcoordination='VIII',\n", " \tcrystal_radius=106.0,\n", " \teconf='1s2',\n", " \tid=214,\n", " \tionic_radius=92.0,\n", " \tmost_reliable=False,\n", " \torigin='calculated, ',\n", " \tspin='',\n", ")],\n", " \tis_monoisotopic=None,\n", " \tis_radioactive=False,\n", " \tisotopes=[<Isotope(Z=3, A=6, mass=6.015122887)>, <Isotope(Z=3, A=7, mass=7.01600344)>],\n", " \tjmol_color='#cc80ff',\n", " \tlattice_constant=3.49,\n", " \tlattice_structure='BCC',\n", " \tmelting_point=553.69,\n", " \tmendeleev_number=1,\n", " \tmetallic_radius=123.0,\n", " \tmetallic_radius_c12=155.0,\n", " \tmolcas_gv_color='#cc80ff',\n", " \tname='Lithium',\n", " \tname_origin='Greek: lithos (stone).',\n", " \tperiod=2,\n", " \tproton_affinity=None,\n", " \tscreening_constants=[<ScreeningConstant(Z= 3, n= 1, s=s, screening= 0.3094)>, <ScreeningConstant(Z= 3, n= 2, s=s, screening= 1.7208)>],\n", " \tsources='Obtained by passing electric charge through melted lithium chloride and from the silicate mineral called spodumene [LiAl(Si2O6)].',\n", " \tspecific_heat=3.489,\n", " \tsymbol='Li',\n", " \tthermal_conductivity=84.8,\n", " \tuses='Used in batteries. Also for certain kinds of glass and ceramics. Some is used in lubricants.',\n", " \tvdw_radius=182.0,\n", " \tvdw_radius_alvarez=212.0,\n", " \tvdw_radius_batsanov=220.00000000000003,\n", " \tvdw_radius_bondi=181.0,\n", " \tvdw_radius_dreiding=None,\n", " \tvdw_radius_mm3=254.99999999999997,\n", " \tvdw_radius_rt=None,\n", " \tvdw_radius_truhlar=None,\n", " \tvdw_radius_uff=245.1,\n", ")]\n" ] } ], "source": [ "'''Single if statement'''\n", "\n", "lithium = None # initialize with any type\n", "\n", "if lithium is None: # test if element has type None \n", " try:\n", " import mendeleev # creates the `name` mendeleev\n", " except ImportError:\n", " print('Installing the \"mendeleev\" package...')\n", " print('')\n", " !pip install mendeleev\n", " import mendeleev\n", " \n", " lithium = mendeleev.element('Li')\n", " print('lithium data: ',[lithium])\n", " \n", "else:\n", " print('lithium variable: ',lithium) # print everything in lithium" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error: test must be 1, 2, or 3.\n" ] } ], "source": [ "'''Testing example'''\n", "\n", "test = 8 # change this to 1, 2 or 3\n", "\n", "# test setup (uses multiway branching)\n", "if test == 1:\n", " print('made to 1')\n", "elif test == 2:\n", " print('made to 2')\n", "elif test == 3:\n", " print('made to 3')\n", "else:\n", " print('Error: test must be 1, 2, or 3.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loops<a id=\"loops\"></a>\n", "Contructs that allow repetitive actions on data. There are two basic types: \n", " 1. `for` loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `For` loops<a id='for'></a>\n", "The general format is (*indentation observed*):\n", "```python\n", "for target in container: # assign container items to target\n", " statements # repeated loop body: (possibly) use target\n", " if test: \n", " break # exit loop now; skip else\n", " if test: \n", " continue # go to top of the loop now\n", " else: # optional else part\n", " statements # if did not hit a `break`\n", "#end for target in object:\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example\n", "```python\n", "for i in range(10): # assign i to objects in range(mtrx.shape[0])\n", " j = 2*i # loop over this statement with varying i\n", " print(j) # print j\n", "#end for i in range(10):\n", "```" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n", "10\n", "12\n", "14\n", "16\n", "18\n" ] } ], "source": [ "'''Simple for loop'''\n", "\n", "for i in range(10): # assign i to objects in range(10)\n", " j = 2*i # loop over this statement with varying i\n", " print(j) # print j" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n", "10\n", "12\n", "14\n", "16\n" ] } ], "source": [ "'''Simple for loop'''\n", "\n", "for i in range(0,18,2): # assign i to objects in range(10,2)\n", " print(i) # print i" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "'''Using a dictionary to create a table'''\n", "\n", "import pandas as pd\n", "\n", "hydrogen = {'symbol':'H', 'atomic number':1, 'group':1, 'period':1, 'isotopes':[1,2,3]}\n", "helium = {'symbol':'He', 'atomic number':2, 'group':18, 'period':1, 'isotopes':[3,4]}\n", "lithium = {'symbol':'Li', 'atomic number':3, 'group':1, 'period':2, 'isotopes':[6,7]}\n", "beryllium = {'symbol':'Be', 'atomic number':4, 'group':2, 'period':2, 'isotopes':[9,10]}\n", "boron = {'symbol':'B', 'atomic number':5, 'group':13, 'period':2, 'isotopes':[10,11]}\n", "\n", "data = {'hydrogen':hydrogen,'helium':helium,'lithium':lithium,'beryllium':beryllium,'boron':boron}\n", "\n", "df1 = pd.DataFrame(data) # pass the dictonary to the data frame" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>hydrogen</th>\n", " <th>helium</th>\n", " <th>lithium</th>\n", " <th>beryllium</th>\n", " <th>boron</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>atomic number</th>\n", " <td>1</td>\n", " <td>2</td>\n", " <td>3</td>\n", " <td>4</td>\n", " <td>5</td>\n", " </tr>\n", " <tr>\n", " <th>group</th>\n", " <td>1</td>\n", " <td>18</td>\n", " <td>1</td>\n", " <td>2</td>\n", " <td>13</td>\n", " </tr>\n", " <tr>\n", " <th>isotopes</th>\n", " <td>[1, 2, 3]</td>\n", " <td>[3, 4]</td>\n", " <td>[6, 7]</td>\n", " <td>[9, 10]</td>\n", " <td>[10, 11]</td>\n", " </tr>\n", " <tr>\n", " <th>period</th>\n", " <td>1</td>\n", " <td>1</td>\n", " <td>2</td>\n", " <td>2</td>\n", " <td>2</td>\n", " </tr>\n", " <tr>\n", " <th>symbol</th>\n", " <td>H</td>\n", " <td>He</td>\n", " <td>Li</td>\n", " <td>Be</td>\n", " <td>B</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " hydrogen helium lithium beryllium boron\n", "atomic number 1 2 3 4 5\n", "group 1 18 1 2 13\n", "isotopes [1, 2, 3] [3, 4] [6, 7] [9, 10] [10, 11]\n", "period 1 1 2 2 2\n", "symbol H He Li Be B" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df1" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "#lithium.series" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "'''Create a similar table using mendeleev data'''\n", "\n", "# the intention here is to use this list as rows labels\n", "index = ['atomic number', 'group', 'isotopes', 'period', 'symbol' ]\n", "\n", "# columwise data in the form of a dictionary\n", "data = dict() # initialize empty dict to hold data\n", "\n", "num_elements = 5 # set total number of chemical elements and atomic number\n", "\n", "for i in range(1,num_elements+1): # loop over indices 0 to ...\n", " ele = mendeleev.element(i) # get chemical element with atomic number i+1\n", " \n", " column_data = list() # initialize empty list to hold the column data\n", " \n", " column_data.append(ele.atomic_number) # get and store atomic number\n", " column_data.append(ele.group_id) # get and store group id\n", " \n", " mass_number_list = list()\n", " for iso in ele.isotopes:\n", " a = iso.mass_number\n", " mass_number_list.append(a)\n", " \n", " #column_data.append( mass_number_list ) \n", " \n", " column_data.append([iso.mass_number for iso in ele.isotopes]) # get and store isotope mass numbers\n", " \n", " column_data.append(ele.period) # get and store element period\n", " column_data.append(ele.symbol) # get and store element symbol\n", " \n", " # store column data in the dictionary key: column label\n", " data[ele.name] = pd.Series(column_data, index) # value: pd.Series\n", " \n", "#end for i in range(5):\n", "\n", "df2 = pd.DataFrame(data) # pass the dictionary to the data frame" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>Hydrogen</th>\n", " <th>Helium</th>\n", " <th>Lithium</th>\n", " <th>Beryllium</th>\n", " <th>Boron</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>atomic number</th>\n", " <td>1</td>\n", " <td>2</td>\n", " <td>3</td>\n", " <td>4</td>\n", " <td>5</td>\n", " </tr>\n", " <tr>\n", " <th>group</th>\n", " <td>1</td>\n", " <td>18</td>\n", " <td>1</td>\n", " <td>2</td>\n", " <td>13</td>\n", " </tr>\n", " <tr>\n", " <th>isotopes</th>\n", " <td>[1, 2, 3]</td>\n", " <td>[3, 4]</td>\n", " <td>[6, 7]</td>\n", " <td>[9]</td>\n", " <td>[10, 11]</td>\n", " </tr>\n", " <tr>\n", " <th>period</th>\n", " <td>1</td>\n", " <td>1</td>\n", " <td>2</td>\n", " <td>2</td>\n", " <td>2</td>\n", " </tr>\n", " <tr>\n", " <th>symbol</th>\n", " <td>H</td>\n", " <td>He</td>\n", " <td>Li</td>\n", " <td>Be</td>\n", " <td>B</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " Hydrogen Helium Lithium Beryllium Boron\n", "atomic number 1 2 3 4 5\n", "group 1 18 1 2 13\n", "isotopes [1, 2, 3] [3, 4] [6, 7] [9] [10, 11]\n", "period 1 1 2 2 2\n", "symbol H He Li Be B" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "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.1" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false } }, "nbformat": 4, "nbformat_minor": 2 }