Skip to content
Snippets Groups Projects
Additional Programming Concepts in Python.ipynb 37.9 KiB
Newer Older
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [2,1]\n",
    "b = a.copy()\n",
    "print(b)\n",
    "a[0] = 1\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, `b` is unaffected by your changes to `a` because the name `b` points to a new copy of the array in memory."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Interactive plots with ipywidgets\n",
    "\n",
    "One of the cool things that is easy to do in Jupter notebooks is to make \"interactive\" plots. \n",
    "\n",
    "For example, in the projectile example above, I may want to be able to play with the angle and see how this changes my trajectory. For this, there is a very easy to use and convenient library called `ipywidgets`.\n",
    "\n",
    "The way it works is we make a function that generates our plot that takes the parameter we want to play with as an argument. We then call an `ipywidgets` function called `interact()`, and it will automatically make a \"live update\" plot in your web browser in which you can adjust the parameter an see how the plot changes. \n",
    "\n",
    "Let's look at an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import interact\n",
    "\n",
    "v0 = 10 # m/s\n",
    "g = 9.8 # m/s^2\n",
    "\n",
    "# We will allow theta to be adjusted and start it at 45 degrees\n",
    "def update_plot(theta=45):\n",
    "    theta *= np.pi/180 # convert to radians\n",
    "    y = -g/(2*v0**2*np.cos(theta)**2)*x**2 + x*np.tan(theta)\n",
    "    plt.plot(x,y)\n",
    "    plt.ylim(-1,6) # Manually set the ylimits\n",
    "    plt.xlabel(\"Distance (m)\")\n",
    "    plt.ylabel(\"Height (m)\")\n",
    "    plt.axhline(0, ls=\":\", c=\"grey\")\n",
    "    plt.show()\n",
    "    \n",
    "# Now we call interact, and give it a tuple specifiying the min, max and step for the theta slider\n",
    "interact(update_plot, theta=(0,89,2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is a bit slow in updating if you wiggle it too much with the mouse, but if you click on the slider and adjust it using the arrow keys on your keyboard, it works pretty well. \n",
    "\n",
    "If you are fitting a line to your data, this can also be very useful for getting a good initial guess:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def update_plot2(slope=0.5):\n",
    "    line = t*slope\n",
    "    plt.plot(t,v, '.')\n",
    "    plt.plot(t,line, lw=4)\n",
    "    plt.xlabel(\"Time (s)\")\n",
    "    plt.ylabel(\"Voltage (V)\")\n",
    "    plt.show()\n",
    "\n",
    "interact(update_plot2, slope=(0,10,0.1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is also easy to make two sliders:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def update_plot3(slope=0.5, offset=0):\n",
    "    line = t*slope+offset\n",
    "    plt.plot(t,v, '.')\n",
    "    plt.plot(t,line, lw=4)\n",
    "    plt.xlabel(\"Time (s)\")\n",
    "    plt.ylabel(\"Voltage (V)\")\n",
    "    plt.show()\n",
    "\n",
    "interact(update_plot3, slope=(0,10,0.1), offset=(-4,3,0.2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Functions\n",
    "\n",
    "### Keyword and optional arguments\n",
    "\n",
    "In addition to the \"positional\" arguments we introduced earlier, python also supports another type of argument: the \"keyword\" argument. These are often used for \"optional\" arguments that you don't neccessarily need but may want to give the user the option of using. The syntax is:\n",
    "\n",
    "```\n",
    "def function_name(var1, optional_var2 = default_value)\n",
    "    ...\n",
    "```\n",
    "\n",
    "The \"default_value\" is the value that the optional argument will have if it is not specified by the user. \n",
    "\n",
    "In python-speak, these \"optional\" arguement as called \"keyword\" arguments, and the normal arguments we introduced above are called \"positional\" arguments. In python, in both defining and using functions, keyword arguments must always come after all of the positional arguments. \n",
    "\n",
    "Here, we will show an example where we use an optional parameter to change the way we print the status sentence. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def print_status4(x, long=True):\n",
    "    if long:\n",
    "        print(\"The value of the first input variable is \", x)\n",
    "    else:\n",
    "        print(\"Val is \", x)\n",
    "\n",
    "print_status4(1)\n",
    "print_status4(2.5, long=True)\n",
    "print_status4(2.4, long=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because python assigns the value of keyword argument variables in the function by matching the keyword and not their position in the list, if you have multiple keyword arguments, you can also change the order of them when you use the function. \n",
    "\n",
    "For example, if I define a function:\n",
    "\n",
    "```\n",
    "def myfunction(x, var1=1, var2=4):\n",
    "    ...\n",
    "```\n",
    "\n",
    "then both of these would do the same thing:\n",
    "\n",
    "```\n",
    "myfunction(1,var1=3, var2=54)\n",
    "myfunction(1,var2=54, var2=3)\n",
    "```\n",
    "\n",
    "Finally, one can also use keywords as a way to send values to functions even if the functions are not defined with keyword arguments. This allows you to change to order of variables you send to a function if you  want. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def myfun(x,y):\n",
    "    print(\"x is\", x)\n",
    "    print(\"y is\", y)    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "myfun(1,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "myfun(2,1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "myfun(x=1,y=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "myfun(y=2,x=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python Error Messages with functions\n",
    "\n",
    "In the first notebook, we learned some of the basics of how to understand python errors.\n",
    "\n",
    "Sometimes, though, if you are using functions from a library, the error messages can get very long, and trickier to understand. \n",
    "\n",
    "Here, we will look at how to dissect an example of a more complicated error you can get from a function in a library and how to figure out where the useful information is."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "plt.plot([1,2], [1,2,3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Wow, that was a really big error message. What do I do with all of this? \n",
    "\n",
    "The most important information is at the very top and at the very bottom (you can just skip the rest for now...). \n",
    "\n",
    "At the top, it shows us the part of our code that triggered the error:\n",
    "\n",
    "<img src=\"resource/asnlib/public/big_error_1.png\"></img>\n",
    "\n",
    "The error type is a `ValueError`, which according to the documentation, indicates \"an argument that has the right type but an inappropriate value\". \n",
    "\n",
    "In the middle there is then a whole bunch of stuff we won't easily understand. What is all of this? This is showing us what is happening inside all the functions of the matplotlib library...probably unless you are a bit of an expert, you will not really understand all of this. \n",
    "\n",
    "We can learn more, though, by looking at the last line:\n",
    "\n",
    "<img src=\"big_error_2.png\"></img>\n",
    "\n",
    "What are `x` and `y`? They are the variable names in the library function in matplotlib where we ended up, so probably also maybe not immediately obvious what they are. But we can see more about the problem: it is complaining that two of the variables do not have the same shape. \n",
    "\n",
    "If we look up at the line in our code that triggered the error, we can see that we have supplied two arguments that have a different number of elements: `plt.plot([1,2], [1,2,3])`\n",
    "\n",
    "It would seem that both the first and second variables of the `plot` function should have the same number of elements. Indeed, if we try:\n",
    "\n",
    "`plt.plot([1,2,3], [1,2,3,])`\n",
    "\n",
    "then the error goes away:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot([1,2,3], [1,2,3,])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Learning objectives list\n",
    "\n",
    "Not crucial since this notebook is optional, but maybe useful to have.\n",
    "\n",
    "**Learning objectives for this notebook:**\n",
    "\n",
    "* Student is able to create and index tuples and lists by hand and using the `range()` operator\n",
    "* Student is able to loop over tuples and lists without indexing\n",
    "* Student is able to extract subsets of lists and tuples using slicing\n",
    "* Student is able to change individual entries of a list using indexing and the assignment operator\n",
    "* Student is able to use built-in functions of lists \n",
    "* Student is able to use indexing to extract substrings from a string\n",
    "* Student is able to use built-in string functions\n",
    "* Student is able to split a string into a list of strings using the `.split()` function\n",
    "* Student is able to search in strings using the `in` operator\n",
    "* Student is able to use formating and the `%` opereator to control how variables are translated into strings\n",
    "* Student is able to predict how variables behave differently for \"mutable\" and \"non-mutable\" objects (call-by-value vs. call-by-reference)\n",
    "* Student is able to use the `ipywidgets` `interact()` function to explore functions using sliders\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "jupytext": {
   "formats": "ipynb,md"
  },
  "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.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": true,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}