{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "## Assignment 3: Functions, conditional statements, and iteration in Python\n", "\n", "Congratulations on completing your first Python assignment! You'll be progressively building on those core skills throughout the semester. \n", "\n", "In this week's notebook, you are first going to learn about functions. Functions are in some ways the bread-and-butter of Python programming. They make code re-usable, as they allow you to apply your code in other contexts and circumstances. You can think about functions this way: while variables store elements of your code (e.g. numbers, strings, lists), functions can store entire chunks of your code, which can in turn be re-used as necessary. \n", "\n", "Functions include a __definition__ and __parameters__, and are specified with `def` as follows: \n", "\n", "```python\n", "def myfunction(parameter1, parameter2, parameter3): \n", " \"\"\"Your code goes here\"\"\"\n", "```\n", "\n", "The `def` command allows you to introduce a function definition. You then specify the __parameters__ within parentheses following the function name, which are like variables that operate within your function. A colon (`:`) then follows the parentheses, and the contents of the function are found beginning on the next line as an indented code block (more on indentation soon). \n", "\n", "After you've defined the function, it can be __called__ by supplying __arguments__ to the parameters you've defined, again within parentheses. For example: \n", "\n", "```python\n", "myfunction(arg1, arg2, arg3)\n", "```\n", "\n", "So how does this all work? Let's try it out!\n", "\n", "At a very basic level, you can define a function without parameters - an _empty_ function. This function will return whatever you've specified after it is called. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def print_five():\n", " print(5)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Now, we call the function: " ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "print_five()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Notice what happened when we called our `print_five` function. As the function has no parameters, it will always give us back 5. Naturally, you're going to want your functions to get more complicated than this - which is what parameters are for. Let's try out a function that has a parameter and performs a basic mathematical operation. " ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.5\n" ] } ], "source": [ "def divide_by_two(x):\n", " print(x / 2)\n", "\n", "divide_by_two(11)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "The function itself is fairly straightforward. Our new function, `divide_by_two`, takes a number, which we are calling `x`. It divides `x` by two, and then prints the result for us. By adding a parameter, however, our function is now re-usable. Let's try it out: " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "27.5\n" ] } ], "source": [ "divide_by_two(55)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "## Now it's your turn! Write a new, empty function that prints your name when called. Call the function.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "### The 'return' statement\n", "\n", "In the above examples, we've created functions that print some result to our screen when called. Often, however, we want our functions to work as part of a larger workflow. This is accomplished with the `return` statement, which allows the output of functions to be assigned to a new variable. \n", "\n", "For example, let's try to assign the result of the `divide_by_two` function to a new variable: " ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6.0\n" ] } ], "source": [ "y = divide_by_two(12)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "And when we ask Python for the value of y: " ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "y" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "We don't get anything back. Now, let's try modifying the function with `return` used instead of `print`. " ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "6.0" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def divide_by_two(x):\n", " return x / 2\n", "\n", "y = divide_by_two(12)\n", "\n", "y" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [], "source": [ "## Now it's your turn! Write a new function that subtracts 7 from a number\n", "## and returns the result. Assign the result of the function to a new \n", "## variable (your argument can be any number you want).\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "### Python and whitespace\n", "\n", "You may have noticed that the statements that follow the function definitions above are __indented__. Python code obeys __whitespace__ for code organization. In many languages, functions, loops, and conditional logic (which we'll get to next week), etc. are organized with curly braces, like the equivalent R code below: \n", "\n", "```r\n", "divide_by_two <- function(x) {\n", " return(x / 2)\n", "}\n", "```\n", "\n", "The R code, like in many languages, is organized in relation to the position of the curly braces, not the positioning of the code itself per se. In Python, curly braces are not used in this capacity. Instead, code is organized by indentation and whitespace. Within a function definition, for example, the code to be executed by the function call should be indented with four spaces beneath the line that contains the `def` statement. In many Python IDEs and the IPython Notebook, the software will already know this and indent your code accordingly. In addition, the Tab key is set to be equivalent to the four spaces in most of these software packages as well. Without proper indentation, however, your code will not run correctly. " ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "ename": "IndentationError", "evalue": "expected an indented block (, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m return x / 3\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" ] } ], "source": [ "def divide_by_three(x):\n", "return x / 3" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "### Named arguments\n", "\n", "Later in the semester, we'll get started using external libraries to do our work, which have many pre-built functions for accomplishing data analysis tasks. Many of these functions are very flexible - which means they have a lot of parameters! It turn, it can be helpful to keep your code organized when you are working with multiple parameters in a function. \n", "\n", "There are a couple ways to supply multiple arguments to a function in Python: \n", "\n", "* In the order they are specified in the function definition; \n", "* As _named_ arguments, in which both the parameter name and the argument are invoked. \n", "\n", "I'll explain this further. Let's define a function, `subtract`, that takes two numbers and will subtract the second number from the first. " ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def subtract(x, y):\n", " return x - y" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Now, we call the function by supplying two arguments to it: " ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subtract(11, 7)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "We could get the same result by supplying _named_ arguments to the function, which take the form of `parameter = argument`: " ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subtract(x = 11, y = 7)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Flipping the order of the arguments will give us a different result _unless_ we name the arguments accordingly. Take a look: " ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "-4" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subtract(7, 11)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subtract(y = 7, x = 11)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Be careful when mixing named and unnamed arguments, however. When arguments are unnamed, Python assumes that you are supplying them in the order of the corresponding parameters in the function definition. As such, you can mix named and unnamed arguments, but unnamed arguments cannot follow named arguments in a function call. " ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subtract(11, y = 7)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "ename": "SyntaxError", "evalue": "positional argument follows keyword argument (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m subtract(x = 11, 7)\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m positional argument follows keyword argument\n" ] } ], "source": [ "subtract(x = 11, 7)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### Docstrings and documenting your code\n", "\n", "You've already learned how to use comments to document your code with the `#` operator, like this: \n", "\n", "```python\n", "# I just commented out this line!\n", "```\n", "\n", "Comments are generally best used for small descriptive statements about your code, or notes to yourself regarding something you'd like to remember. More formal documentation of your code - e.g. what you functions are supposed to do - are best handled through __docstrings__. Docstrings are enclosed in triple quotes (`\"\"\"`), and can go beneath the function definition to explain its components. Let's try using a docstring to explain, in basic terms, the contents of our `subtract` function. " ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def subtract(x, y):\n", " \"\"\"\n", " Subtract one number from another.\n", "\n", " Parameters:\n", " -----------\n", " x: The number you would like to subtract a quantity from (the minuend).\n", " y: The quantity you would like to subtract from x (the subtrahend).\n", " \"\"\"\n", "\n", " return x - y" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "You've now created a new function, `subtract()` with associated help documentation. To view the documentation, you can use the built-in `help()` function to print the docstring, or type the function name followed by a question mark to pop up the documentation at the bottom of the screen. Try it out!" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function subtract in module __main__:\n", "\n", "subtract(x, y)\n", " Subtract one number from another.\n", " \n", " Parameters:\n", " -----------\n", " x: The number you would like to subtract a quantity from (the minuend).\n", " y: The quantity you would like to subtract from x (the subtrahend).\n", "\n" ] } ], "source": [ "help(subtract)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "subtract?" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Now it is your turn!\n", "\n", "# Create a new function, \"multiply\", that multiplies two numbers together.\n", "# Write a docstring in the function definition that describes what the function does,\n", "# and explains the parameters to the user.\n", "# Run your function and call it to test it out.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "### Booleans and conditional statements\n", "\n", "The above functions we've written perform the same operations for any input values that are passed to them. When writing programs, however, you'll often have to design them to be flexible to user input where outcomes may vary based on what users supply to the program. In regards to data analysis, you might want to produce a particular type of chart if the data are structured a certain way, which wouldn't work in another scenario. You can build this type of logic into your programs with __conditional statements__. \n", "\n", "Before we get into this, however, I want to introduce __booleans__ in Python. You may have heard this term before in other classes. Booleans in Python are the values `True` and `False`; they can be used to evaluate, understandably, if a condition is true or not. For example: " ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 > 2" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 > 3" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 == 3" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 != 3" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "In the above lines of code, we used basic mathematical operators to see if conditions are true or false. When we asked Python if 3 is greater than 2, it told us it was True; when we asked it if 2 is greater than 3, it said False. Such true/false logic can be used with conditional statements in your code. To do this, you'll often use __conditional operators__, which you'll be familiar with from basic mathematics, possibly with a couple exceptions. Conditional operators in Python are as follows: \n", "\n", "* `<` Less than\n", "* `>` Greater than\n", "* `<=` Less than or equal to\n", "* `>=` Greater than or equal to\n", "* `==` Is equal to\n", "* `!=` Is not equal to\n", "\n", "As humans, we use conditional logic all of the time without really thinking about it. For example, __if__ I am hungry, I'll probably go eat something; otherwise, I won't. Such logic can be expressed in Python as a series of `if`, `elif` (which means _else if_), and `else` statements. \n", "\n", "Let's try to express this now in code in basic terms. This is made-up code, so we don't need to understand everything, but here are the basics of it. We define a function, `hungry`, that measures the biological/psychological properties that govern hunger reflexes in the human body. We say, hypothetically, that a hunger index value encapsulating these properties that exceeds 100 means that a person is hungry; in turn, the function returns `True`. Otherwise, it returns `False`. " ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def hungry(hunger_index):\n", " if hunger_index > 100:\n", " return True\n", " else:\n", " return False\n", "\n", "hungry(103)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hungry(88)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "We can then pass a variable `kyle`, which represents my hunger index, to the function. The function then checks to see if I am hungry, and returns `True` if I am, and `False` otherwise. These results can then be embedded in other workflows, in which you program Python to perform different tasks depending on the function results. For example: \n", "\n", "```python\n", "if hungry(kyle): \n", " eat()\n", "else: \n", " stay_put()\n", "```\n", "\n", "As you can see above, this can be simplified in Python as the code `if hungry(kyle)` checks to see if the returned value is `True`. If I am hungry, the code calls an unseen `eat()` function telling me to go eat; otherwise, it tells me to stay put with an unseen `stay_put()` function. \n", "\n", "Simple enough, right? Not quite. I'm hungry right now, but I'm not currently eating. Why is that the case? Well... I have to get this assignment written for you! While I am hungry, my level of hunger is not so debilitating that I am unable to work, and I know that finishing my work is a higher priority than eating at the moment. In reality, there are countless conditions that influence whether we eat or not beyond simply how hungry we are. For example - is there food accessible? Are you in a place where it is socially acceptable to eat? Perhaps you are at a party where pizza is available - you aren't hungry, but you eat it anyway? Your brain processes all of this conditional logic at once as you make decisions, so we aren't always used to thinking explicitly about conditionals in such discrete ways. However, to get a computer to understand this, you have to make it explicit in your code!\n", "\n", "The `hungry` function we defined above used conditional logic, telling Python to return `True` or `False` depending on the value of the hunger index. Note that the `if` statement starts on a new indented line of code beneath the function definition, and itself is followed by a colon; the code associated with the `if` statement then follows on another, indented line of code. The same goes for the `else` statement beneath it. You should be getting a sense now of style rules in Python, and the importance of whitespace for code organization, which applies to conditional statements as well. \n", "\n", "Now I'd like you to try to replicate this yourself! Define a function called `greater_than_two` that checks to see if a number is greater than 2 or not. Call the function. " ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [], "source": [ "### Your code goes here!\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "### Loops\n", "\n", "In programming, you will often want to do an operation multiple times, or carry out some process over a list of values that you've created. To do this, you will frequently turn to __iterators__. \n", "\n", "The most commonly used iterators in Python are `for` and `while`. A `for` loop carries out an action, or set of actions, for every element that you tell it to. Let's give it a try in very simple terms. I've created a list of teams in the Big 12 below; we'll loop through this list with `for` and concatenate another string to each element. " ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [], "source": [ "big12 = [\"TCU Horned Frogs\", \"Baylor Bears\", \"Oklahoma Sooners\", \"Oklahoma State Cowboys\", \"Texas Longhorns\", \n", " \"Texas Tech Red Raiders\", \"West Virginia Mountaineers\", \"Kansas Jayhawks\", \"Kansas State Wildcats\",\n", " \"Iowa State Cyclones\"]" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "TCU Horned Frogs are in the Big 12.\n", "Baylor Bears are in the Big 12.\n", "Oklahoma Sooners are in the Big 12.\n", "Oklahoma State Cowboys are in the Big 12.\n", "Texas Longhorns are in the Big 12.\n", "Texas Tech Red Raiders are in the Big 12.\n", "West Virginia Mountaineers are in the Big 12.\n", "Kansas Jayhawks are in the Big 12.\n", "Kansas State Wildcats are in the Big 12.\n", "Iowa State Cyclones are in the Big 12.\n" ] } ], "source": [ "for team in big12: # You can read this here as \"for every team in the Big 12....\n", " print(team + \" are in the Big 12.\") # ... print the name of the team along with \"are in the Big 12.\"" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "A couple notes about the above code. Notice that I'm using `team` as a temporary variable that will successively store each value of the list as we loop through it. This variable, `team`, takes on each value of the list in turn; and presently stores the last value of the list. " ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'Iowa State Cyclones'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "team" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "As such, this is how the `for` loop works. `for` tells Python to evaluate every element of the list `big12`; these elements will be represented by the variable `team`. The loop then walks through the list `big12` and prints the specified text __for__ every element in the list. This `for` loop is equivalent, then, to: \n", "\n", "```python\n", "print(\"TCU Horned Frogs are in the Big 12\")\n", "print(\"Baylor Bears are in the Big 12\")\n", "print(\"Oklahoma Sooners are in the Big 12\")\n", "\n", "# ... and so forth\n", "\n", "```\n", "\n", "but you don't really want to do that manually, especially when you might have thousands of strings to evaluate. In turn, the `for` loop does the work for you, which is one of the main benefits of programming. \n", "\n", "Also, I'd like you to notice the structure of the loop. Like functions, loops obey __whitespace__ rules for code organization, and will fail if your code is not properly indented. The first line of the loop - in this case `for team in big12` - is not indented, and is followed by a colon. Everything else contained in the loop is found in an indented block on the line(s) following the `for` loop call. As with functions, your loop will fail without proper indentation. " ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "ename": "IndentationError", "evalue": "expected an indented block (, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m print(team + \" are in the Big 12.\")\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" ] } ], "source": [ "for team in big12: \n", "print(team + \" are in the Big 12.\")" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Now let's say you want to create a new list of the \"...are in the Big 12\" elements. There are a couple ways to do this. In the first, you define an empty list object, then populate the list with the for loop and the `append` method, as shown below. " ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['TCU Horned Frogs are in the Big 12.',\n", " 'Baylor Bears are in the Big 12.',\n", " 'Oklahoma Sooners are in the Big 12.',\n", " 'Oklahoma State Cowboys are in the Big 12.',\n", " 'Texas Longhorns are in the Big 12.',\n", " 'Texas Tech Red Raiders are in the Big 12.',\n", " 'West Virginia Mountaineers are in the Big 12.',\n", " 'Kansas Jayhawks are in the Big 12.',\n", " 'Kansas State Wildcats are in the Big 12.',\n", " 'Iowa State Cyclones are in the Big 12.']" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "teams = [] # The empty brackets designate an empty list, which you'll fill up with the loop.\n", "\n", "for team in big12:\n", " teams.append(team + \" are in the Big 12.\")\n", "\n", "teams" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "You can also do the same thing with something called __list comprehension__. List comprehension allows for the creation of a new list with one line of code. In this case, the `for` loop is embedded within the statement you make. Below is an example: " ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['TCU Horned Frogs are in the Big 12.',\n", " 'Baylor Bears are in the Big 12.',\n", " 'Oklahoma Sooners are in the Big 12.',\n", " 'Oklahoma State Cowboys are in the Big 12.',\n", " 'Texas Longhorns are in the Big 12.',\n", " 'Texas Tech Red Raiders are in the Big 12.',\n", " 'West Virginia Mountaineers are in the Big 12.',\n", " 'Kansas Jayhawks are in the Big 12.',\n", " 'Kansas State Wildcats are in the Big 12.',\n", " 'Iowa State Cyclones are in the Big 12.']" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "teams2 = [team + \" are in the Big 12.\" for team in big12]\n", "\n", "teams2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "You can use methods and functions in your list comprehension as well, as in the example below: " ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['tcu hORNED fROGS',\n", " 'bAYLOR bEARS',\n", " 'oKLAHOMA sOONERS',\n", " 'oKLAHOMA sTATE cOWBOYS',\n", " 'tEXAS lONGHORNS',\n", " 'tEXAS tECH rED rAIDERS',\n", " 'wEST vIRGINIA mOUNTAINEERS',\n", " 'kANSAS jAYHAWKS',\n", " 'kANSAS sTATE wILDCATS',\n", " 'iOWA sTATE cYCLONES']" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "swap = [name.swapcase() for name in big12]\n", "\n", "swap" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Loops also work for strings - though in this case the loop will iterate through each character contained in your string. An example: " ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The index of T is 0\n", "The index of e is 1\n", "The index of x is 2\n", "The index of a is 3\n", "The index of s is 4\n", "The index of is 5\n", "The index of C is 6\n", "The index of h is 7\n", "The index of r is 8\n", "The index of i is 9\n", "The index of s is 10\n", "The index of t is 11\n", "The index of i is 12\n", "The index of a is 13\n", "The index of n is 14\n", "The index of is 15\n", "The index of U is 16\n", "The index of n is 17\n", "The index of i is 18\n", "The index of v is 19\n", "The index of e is 20\n", "The index of r is 21\n", "The index of s is 22\n", "The index of i is 23\n", "The index of t is 24\n", "The index of y is 25\n" ] } ], "source": [ "tcu = \"Texas Christian University\"\n", "\n", "idx = 0\n", "for character in tcu:\n", " print(\"The index of \" + character + \" is \" + str(idx))\n", " idx = idx + 1" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "#### The `while` loop\n", "\n", "`for` is not the only loop you'll come across in Python. You can also specify a `while` loop, which will run a loop until a given condition is satisfied. I'll give you an example below. Let's say you only want to return the first five elements of your list. While you could do this with indexing (which is simpler), let's try the `while` loop instead. " ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['TCU Horned Frogs',\n", " 'Baylor Bears',\n", " 'Oklahoma Sooners',\n", " 'Oklahoma State Cowboys',\n", " 'Texas Longhorns']" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "newlist = []\n", "\n", "i = 0\n", "\n", "while i < 5:\n", " newlist.append(big12[i])\n", " i = i + 1\n", "\n", "newlist" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Have a look at what we did. We created an empty list, and set a new variable, `i`, to 0. We then looped through the elements of the list index by index, adding 1 to `i` with each run of the loop, and then stopping the code when `i` became equal to 5. In turn, we got back the elements of the `big12` list indexed 0 to 4, which are the first five elements. \n", "\n", "Be careful with while loops, however. If you don't specify them correctly, you can get stuck in an infinite loop, which will not stop! For example, if we had not continued to add 1 to `i`, the loop would have never stopped and would have kept iterating through the list. This can cause your computer to lock up, as it is infinitely trying to carry out an operation! I've been there a few times..." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "## Exercises\n", "\n", "As with the previous Jupyter Notebook you worked with, I'll ask you to complete a series of small exercises below to get full credit for this week's assignment. Some of these exercises will build upon the skills you learned last week - so be prepared!\n", "\n", "__Exercise 1:__ Explain, in your own words, the difference between using `print` and `return` for the output of a function. Write your response below, in this Markdown cell. \n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__Exercise 2:__ Write a function called `make_big` that takes a lowercase string as input and prints the string with all capital letters. Create a new variable and assign to it a string with all lowercase letters, then call the `make_big` function with that variable as its argument. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Your answer goes here!\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__Exercise 3:__ Write a function called `first_word` that takes a list of character strings as input and returns the first element of the list in alphabetical order. For example, your function should work like this: \n", "\n", "```python\n", "\n", "students = ['Mary', 'Zelda', 'Jimmy', 'Jack', 'Bartholomew', 'Gertrude']\n", "\n", "first_word(students)\n", "\n", "'Bartholomew' # The result\n", "\n", "```\n", "\n", "_Hint:_ You'll need to first sort your list in the function to accomplish this, then identify the first element. Within a function, it is a good idea to use multiple lines of code to separate out the different steps. Just make sure all the code that belongs to the function is indented!\n", "\n", "After you've written the function, run it by supplying the list `teams` to your function as an argument to test it. " ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "teams = ['Stars', 'Cowboys', 'Rangers', 'Mavericks', 'FC Dallas']\n", "\n", "# Your code goes below!\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__Exercise 4:__ Explain, in your own words, the difference between a `for` loop and a `while` loop. Write your response below in this Markdown cell. " ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__Exercise 5 (from your textbook, p. 49):__ \n", "\n", "> If you are given three sticks, you may or may not be able to arrange them in a triangle.\n", "For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that\n", "you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a\n", "simple test to see if it is possible to form a triangle:\n", "If any of the three lengths is greater than the sum of the other two, then you cannot\n", "form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they\n", "form what is called a “degenerate” triangle.)\n", "> \n", "> Write a function named `is_triangle` that takes three integers as arguments, and that returns either `True` or `False` depending on whether you can or cannot form a triangle from sticks with the given lengths. _Hint_: you'll need to use \n", "\n", "For example: \n", "\n", "```python\n", "is_triangle(2, 2, 11)\n", "\n", "False\n", "\n", "is_triangle(5, 5, 6)\n", "\n", "True\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "## Your code goes here!\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__Exercise 6__: Sequences of numbers in Python can be generated by typing them out, as you've learned how to do in this class. However, they can also be produced by the built-in `range` function, which can simplify things for you significantly if you need to generate a long list of integers. `range` has three parameters: `start`, which is the first integer you want to start with; `stop`, which is the first integer you __don't__ want to include, and `step`, which optionally specifies the integer interval. For example: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = range(1, 21, 5)\n", "\n", "x" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "type(x)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "We've created a __range__ object which conforms to the arguments we supplied to the `range` function. Notably, the range object can be looped through:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "for y in x:\n", " print(y)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "If need be, your range object can also be converted to a list with the `list` function. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list(x)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Your job in Exercise 3 is to use the `range` function to print the following text to the screen: \n", "\n", "```\n", "2!\n", "4!\n", "6!\n", "8!\n", "Who do we appreciate?\n", "```\n", "\n", "The printing of the numbers should be done in a loop over the numbers generated by the `range` function. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "## Your code goes here!\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (system-wide)", "language": "python", "metadata": { "cocalc": { "description": "Python 3 programming language", "priority": 100, "url": "https://www.python.org/" } }, "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.8.2" } }, "nbformat": 4, "nbformat_minor": 4 }