{ "metadata": { "name": "if_statements" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "If Statements\n", "===\n", "By allowing you to respond selectively to different situations and conditions, if statements open up whole new possibilities for your programs. In this section, you will learn how to test for certain conditions, and then respond in appropriate ways to those conditions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Previous: Introducing Functions](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/introducing_functions.ipynb) | \n", "[Home](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/index.ipynb) |\n", "[Next: While Loops and Input](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/while_input.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Contents\n", "===\n", "- [What is an *if* statement?](#what)\n", " - [Example](#example)\n", "- [Logical tests](#logical_tests)\n", " - [Equality](#equality)\n", " - [Inequality](#inequality)\n", " - [Other inequalities](#other_inequalities)\n", " - [Checking if an item is in a list](#in_list)\n", " - [Exercises](#exercises_logical_tests)\n", "- [The if-elif...else chain](#if-elif-else)\n", " - [Simple if statements](#simple_if)\n", " - [if-else statements](#if-else)\n", " - [if-elif...else chains](#if-elif-else_chains)\n", " - [Exercises](#exercises_if-elif-else)\n", "- [More than one passing test](#more_than_one)\n", "- [True and False values](#true_false)\n", "- [Overall Challenges](#overall_challenges)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is an *if* statement?\n", "===\n", "An *if* statement tests for a condition, and then responds to that condition. If the condition is true, then whatever action is listed next gets carried out. You can test for multiple conditions at the same time, and respond appropriately to each condition.\n", "\n", "Example\n", "---\n", "Here is an example that shows a number of the desserts I like. It lists those desserts, but lets you know which one is my favorite." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# A list of desserts I like.\n", "desserts = ['ice cream', 'chocolate', 'apple crisp', 'cookies']\n", "favorite_dessert = 'apple crisp'\n", "\n", "# Print the desserts out, but let everyone know my favorite dessert.\n", "for dessert in desserts:\n", " if dessert == favorite_dessert:\n", " # This dessert is my favorite, let's let everyone know!\n", " print(\"%s is my favorite dessert!\" % dessert.title())\n", " else:\n", " # I like these desserts, but they are not my favorite.\n", " print(\"I like %s.\" % dessert)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "I like ice cream.\n", "I like chocolate.\n", "Apple Crisp is my favorite dessert!\n", "I like cookies.\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### What happens in this program?\n", "\n", "- The program starts out with a list of desserts, and one dessert is identified as a favorite.\n", "- The for loop runs through all the desserts.\n", "- Inside the for loop, each item in the list is tested.\n", " - If the current value of *dessert* is equal to the value of *favorite_dessert*, a message is printed that this is my favorite.\n", " - If the current value of *dessert* is not equal to the value of *favorite_dessert*, a message is printed that I just like the dessert.\n", " \n", "You can test as many conditions as you want in an if statement, as you will see in a little bit." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Logical Tests\n", "===\n", "Every if statement evaluates to *True* or *False*. *True* and *False* are Python keywords, which have special meanings attached to them. You can test for the following conditions in your if statements:\n", "\n", "- [equality](#equality) (==)\n", "- [inequality](#inequality) (!=)\n", "- [other inequalities](#other_inequalities)\n", " - greater than (>)\n", " - greater than or equal to (>=)\n", " - less than (<)\n", " - less than or equal to (<=)\n", "- [You can test if an item is **in** a list.](#in_list)\n", "\n", "### Whitespace\n", "Remember [learning about](http://introtopython.org/lists_tuples.html#pep8) PEP 8? There is a [section of PEP 8](http://www.python.org/dev/peps/pep-0008/#other-recommendations) that tells us it's a good idea to put a single space on either side of all of these comparison operators. If you're not sure what this means, just follow the style of the examples you see below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Equality\n", "---\n", "Two items are *equal* if they have the same value. You can test for equality between numbers, strings, and a number of other objects which you will learn about later. Some of these results may be surprising, so take a careful look at the examples below.\n", "\n", "In Python, as in many programming languages, two equals signs tests for equality.\n", "\n", "**Watch out!** Be careful of accidentally using one equals sign, which can really throw things off because that one equals sign actually sets your item to the value you are testing for!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "5 == 5" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "True" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "3 == 5 " ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "False" ] } ], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "5 == 5.0" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 24, "text": [ "True" ] } ], "prompt_number": 24 }, { "cell_type": "code", "collapsed": false, "input": [ "'eric' == 'eric'" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 8, "text": [ "True" ] } ], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [ "'Eric' == 'eric'" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 9, "text": [ "False" ] } ], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "'Eric'.lower() == 'eric'.lower()" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 10, "text": [ "True" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "'5' == 5" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 11, "text": [ "False" ] } ], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "'5' == str(5)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 12, "text": [ "True" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Inequality\n", "---\n", "Two items are *inequal* if they do not have the same value. In Python, we test for inequality using the exclamation point and one equals sign.\n", "\n", "Sometimes you want to test for equality and if that fails, assume inequality. Sometimes it makes more sense to test for inequality directly." ] }, { "cell_type": "code", "collapsed": false, "input": [ "3 != 5" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 13, "text": [ "True" ] } ], "prompt_number": 13 }, { "cell_type": "code", "collapsed": false, "input": [ "5 != 5" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 14, "text": [ "False" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "'Eric' != 'eric'" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 18, "text": [ "True" ] } ], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other Inequalities\n", "---\n", "### greater than" ] }, { "cell_type": "code", "collapsed": false, "input": [ "5 > 3" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 16, "text": [ "True" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### greater than or equal to" ] }, { "cell_type": "code", "collapsed": false, "input": [ "5 >= 3" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 19, "text": [ "True" ] } ], "prompt_number": 19 }, { "cell_type": "code", "collapsed": false, "input": [ "3 >= 3" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 20, "text": [ "True" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### less than" ] }, { "cell_type": "code", "collapsed": false, "input": [ "3 < 5" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 21, "text": [ "True" ] } ], "prompt_number": 21 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### less than or equal to" ] }, { "cell_type": "code", "collapsed": false, "input": [ "3 <= 5" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 22, "text": [ "True" ] } ], "prompt_number": 22 }, { "cell_type": "code", "collapsed": false, "input": [ "3 <= 3" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 23, "text": [ "True" ] } ], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Checking if an item is **in** a list\n", "---\n", "You can check if an item is in a list using the **in** keyword." ] }, { "cell_type": "code", "collapsed": false, "input": [ "vowels = ['a', 'e', 'i', 'o', 'u']\n", "'a' in vowels" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 25, "text": [ "True" ] } ], "prompt_number": 25 }, { "cell_type": "code", "collapsed": false, "input": [ "vowels = ['a', 'e', 'i', 'o', 'u']\n", "'b' in vowels" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 26, "text": [ "False" ] } ], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercises\n", "---\n", "#### True and False\n", "- Write a program that consists of at least ten lines, each of which has a logical statement on it. The output of your program should be 5 **True**s and 5 **False**s.\n", "- Note: You will probably need to write `print(5 > 3)`, not just `5 > 3`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The if-elif...else chain\n", "===\n", "You can test whatever series of conditions you want to, and you can test your conditions in any combination you want." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Simple if statements\n", "---\n", "The simplest test has a single **if** statement, and a single statement to execute if the condition is **True**." ] }, { "cell_type": "code", "collapsed": false, "input": [ "dogs = ['willie', 'hootz', 'peso', 'juno']\n", "\n", "if len(dogs) > 3:\n", " print(\"Wow, we have a lot of dogs here!\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Wow, we have a lot of dogs here!\n" ] } ], "prompt_number": 27 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this situation, nothing happens if the test does not pass." ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2]\n", "dogs = ['willie', 'hootz']\n", "\n", "if len(dogs) > 3:\n", " print(\"Wow, we have a lot of dogs here!\")" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 28 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that there are no errors. The condition `len(dogs) > 3` evaluates to False, and the program moves on to any lines after the **if** block." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "if-else statements\n", "---\n", "Many times you will want to respond in two possible ways to a test. If the test evaluates to **True**, you will want to do one thing. If the test evaluates to **False**, you will want to do something else. The **if-else** structure lets you do that easily. Here's what it looks like:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "dogs = ['willie', 'hootz', 'peso', 'juno']\n", "\n", "if len(dogs) > 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "else:\n", " print(\"Okay, this is a reasonable number of dogs.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Wow, we have a lot of dogs here!\n" ] } ], "prompt_number": 30 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our results have not changed in this case, because if the test evaluates to **True** only the statements under the **if** statement are executed. The statements under **else** area only executed if the test fails:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2]\n", "dogs = ['willie', 'hootz']\n", "\n", "if len(dogs) > 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "else:\n", " print(\"Okay, this is a reasonable number of dogs.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Okay, this is a reasonable number of dogs.\n" ] } ], "prompt_number": 31 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The test evaluated to **False**, so only the statement under `else` is run." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "if-elif...else chains\n", "---\n", "Many times, you will want to test a series of conditions, rather than just an either-or situation. You can do this with a series of if-elif-else statements\n", "\n", "There is no limit to how many conditions you can test. You always need one if statement to start the chain, and you can never have more than one else statement. But you can have as many elif statements as you want." ] }, { "cell_type": "code", "collapsed": false, "input": [ "dogs = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']\n", "\n", "if len(dogs) >= 5:\n", " print(\"Holy mackerel, we might as well start a dog hostel!\")\n", "elif len(dogs) >= 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "else:\n", " print(\"Okay, this is a reasonable number of dogs.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Holy mackerel, we might as well start a dog hostel!\n" ] } ], "prompt_number": 32 }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is important to note that in situations like this, only the first test is evaluated. In an if-elif-else chain, once a test passes the rest of the conditions are ignored." ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2]\n", "dogs = ['willie', 'hootz', 'peso', 'monty']\n", "\n", "if len(dogs) >= 5:\n", " print(\"Holy mackerel, we might as well start a dog hostel!\")\n", "elif len(dogs) >= 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "else:\n", " print(\"Okay, this is a reasonable number of dogs.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Wow, we have a lot of dogs here!\n" ] } ], "prompt_number": 33 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first test failed, so Python evaluated the second test. That test passed, so the statement corresponding to `len(dogs) >= 3` is executed." ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2]\n", "dogs = ['willie', 'hootz']\n", "\n", "if len(dogs) >= 5:\n", " print(\"Holy mackerel, we might as well start a dog hostel!\")\n", "elif len(dogs) >= 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "else:\n", " print(\"Okay, this is a reasonable number of dogs.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Okay, this is a reasonable number of dogs.\n" ] } ], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this situation, the first two tests fail, so the statement in the else clause is executed. Note that this statement would be executed even if there are no dogs at all:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2]\n", "dogs = []\n", "\n", "if len(dogs) >= 5:\n", " print(\"Holy mackerel, we might as well start a dog hostel!\")\n", "elif len(dogs) >= 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "else:\n", " print(\"Okay, this is a reasonable number of dogs.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Okay, this is a reasonable number of dogs.\n" ] } ], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that you don't have to take any action at all when you start a series of if statements. You could simply do nothing in the situation that there are no dogs by replacing the `else` clause with another `elif` clause:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[8]\n", "dogs = []\n", "\n", "if len(dogs) >= 5:\n", " print(\"Holy mackerel, we might as well start a dog hostel!\")\n", "elif len(dogs) >= 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "elif len(dogs) >= 1:\n", " print(\"Okay, this is a reasonable number of dogs.\")" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 36 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case, we only print a message if there is at least one dog present. Of course, you could add a new `else` clause to respond to the situation in which there are no dogs at all:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[10,11]\n", "dogs = []\n", "\n", "if len(dogs) >= 5:\n", " print(\"Holy mackerel, we might as well start a dog hostel!\")\n", "elif len(dogs) >= 3:\n", " print(\"Wow, we have a lot of dogs here!\")\n", "elif len(dogs) >= 1:\n", " print(\"Okay, this is a reasonable number of dogs.\")\n", "else:\n", " print(\"I wish we had a dog here.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "I wish we had a dog here.\n" ] } ], "prompt_number": 37 }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, the if-elif-else chain lets you respond in very specific ways to any given situation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercises\n", "---\n", "#### Three is a Crowd\n", "- Make a list of names that includes at least four people.\n", "- Write an if test that prints a message about the room being crowded, if there are more than three people in your list.\n", "- Modify your list so that there are only two people in it. Use one of the methods for removing people from the list, don't just redefine the list.\n", "- Run your if test again. There should be no output this time, because there are less than three people in the list.\n", "- **Bonus:** Store your if test in a function called something like `crowd_test`.\n", "\n", "#### Three is a Crowd - Part 2\n", "- Save your program from *Three is a Crowd* under a new name.\n", "- Add an `else` statement to your if tests. If the `else` statement is run, have it print a message that the room is not very crowded.\n", "\n", "#### Six is a Mob\n", "- Save your program from *Three is a Crowd - Part 2* under a new name.\n", "- Add some names to your list, so that there are at least six people in the list.\n", "- Modify your tests so that\n", " - If there are more than 5 people, a message is printed about there being a mob in the room.\n", " - If there are 3-5 people, a message is printed about the room being crowded.\n", " - If there are 1 or 2 people, a message is printed about the room not being crowded.\n", " - If there are no people in the room, a message is printed abou the room being empty." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More than one passing test\n", "===\n", "In all of the examples we have seen so far, only one test can pass. As soon as the first test passes, the rest of the tests are ignored. This is really good, because it allows our code to run more efficiently. Many times only one condition can be true, so testing every condition after one passes would be meaningless.\n", "\n", "There are situations in which you want to run a series of tests, where every single test runs. These are situations where any or all of the tests could pass, and you want to respond to each passing test. Consider the following example, where we want to greet each dog that is present:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "dogs = ['willie', 'hootz']\n", "\n", "if 'willie' in dogs:\n", " print(\"Hello, Willie!\")\n", "if 'hootz' in dogs:\n", " print(\"Hello, Hootz!\")\n", "if 'peso' in dogs:\n", " print(\"Hello, Peso!\")\n", "if 'monty' in dogs:\n", " print(\"Hello, Monty!\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello, Willie!\n", "Hello, Hootz!\n" ] } ], "prompt_number": 38 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we had done this using an if-elif-else chain, only the first dog that is present would be greeted:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[6,7,8,9,10,11]\n", "dogs = ['willie', 'hootz']\n", "\n", "if 'willie' in dogs:\n", " print(\"Hello, Willie!\")\n", "elif 'hootz' in dogs:\n", " print(\"Hello, Hootz!\")\n", "elif 'peso' in dogs:\n", " print(\"Hello, Peso!\")\n", "elif 'monty' in dogs:\n", " print(\"Hello, Monty!\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello, Willie!\n" ] } ], "prompt_number": 41 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, this could be written much more cleanly using lists and for loops. See if you can follow this code." ] }, { "cell_type": "code", "collapsed": false, "input": [ "dogs_we_know = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']\n", "dogs_present = ['willie', 'hootz']\n", "\n", "# Go through all the dogs that are present, and greet the dogs we know.\n", "for dog in dogs_present:\n", " if dog in dogs_we_know:\n", " print(\"Hello, %s!\" % dog.title())" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello, Willie!\n", "Hello, Hootz!\n" ] } ], "prompt_number": 43 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the kind of code you should be aiming to write. It is fine to come up with code that is less efficient at first. When you notice yourself writing the same kind of code repeatedly in one program, look to see if you can use a loop or a function to make your code more efficient." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "True and False values\n", "===\n", "Every value can be evaluated as True or False. The general rule is that any non-zero or non-empty value will evaluate to True. If you are ever unsure, you can open a Python terminal and write two lines to find out if the value you are considering is True or False. Take a look at the following examples, keep them in mind, and test any value you are curious about. I am using a slightly longer test just to make sure something gets printed each time." ] }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2]\n", "if 0:\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to False.\n" ] } ], "prompt_number": 60 }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2]\n", "if 1:\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to True.\n" ] } ], "prompt_number": 61 }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2,3]\n", "# Arbitrary non-zero numbers evaluate to True.\n", "if 1253756:\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to True.\n" ] } ], "prompt_number": 62 }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2,3]\n", "# Negative numbers are not zero, so they evaluate to True.\n", "if -1:\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to True.\n" ] } ], "prompt_number": 63 }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2,3]\n", "# An empty string evaluates to False.\n", "if '':\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to False.\n" ] } ], "prompt_number": 64 }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2,3]\n", "# Any other string, including a space, evaluates to True.\n", "if ' ':\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to True.\n" ] } ], "prompt_number": 66 }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2,3]\n", "# Any other string, including a space, evaluates to True.\n", "if 'hello':\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to True.\n" ] } ], "prompt_number": 67 }, { "cell_type": "code", "collapsed": false, "input": [ "###highlight=[2,3]\n", "# None is a special object in Python. It evaluates to False.\n", "if None:\n", " print(\"This evaluates to True.\")\n", "else:\n", " print(\"This evaluates to False.\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This evaluates to False.\n" ] } ], "prompt_number": 68 }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Overall Challenges\n", "===\n", "#### Alien Points\n", "- Make a list of ten aliens, each of which is one color: 'red', 'green', or 'blue'.\n", " - You can shorten this to 'r', 'g', and 'b' if you want, but if you choose this option you have to include a comment explaining what r, g, and b stand for.\n", "- Red aliens are worth 5 points, green aliens are worth 10 points, and blue aliens are worth 20 points.\n", "- Use a for loop to determine the number of points a player would earn for destroying all of the aliens in your list.\n", "- [hint](#hint_alien_points)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[top](#)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- - -\n", "[Previous: Introducing Functions](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/introducing_functions.ipynb) | \n", "[Home](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/index.ipynb) |\n", "[Next: While Loops and Input](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/while_input.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hints\n", "===\n", "These are placed at the bottom, so you can have a chance to solve exercises without seeing any hints.\n", "\n", "#### Alien Invaders\n", "- After you define your list of aliens, set a variable called `current_score` or `current_points` equal to 0.\n", "- Inside your for loop, write a series of if tests to determine how many points to add to the current score.\n", "- To keep a running total, use the syntax `current_score = current_score + points`, where *points* is the number of points for the current alien." ] } ], "metadata": {} } ] }