Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Summer Enrichment Program Python for Beginners Python for Beginners......................................................................................1 Lesson 0. A Short Intro....................................................................................................... 2 Lesson 1. My First Python Program ................................................................................... 3 Lesson 2. Data Types .......................................................................................................... 4 Integers and Floats.......................................................................................................... 4 Strings ............................................................................................................................. 6 Lesson 3. Variables ............................................................................................................. 8 Lesson 4. Data Structures................................................................................................. 12 Lists ............................................................................................................................... 12 Dictionaries ....................................................................................................................15 Lesson 5. If Statements..................................................................................................... 18 Structure........................................................................................................................ 19 How If Statements Work .............................................................................................. 20 Lesson 6. Loops................................................................................................................. 24 For loops........................................................................................................................ 24 While loops.................................................................................................................... 27 Appendix A. Solutions ...................................................................................................... 30 Summer Enrichment Program Lesson 0. A Short Intro First, if you haven't heard of python already, you might be wondering what it means. In addition to being a snake-like animal, python is also a programming language. It is named after Monty Python, a famous British comedy troupe that made such films as "The Meaning of Life" and "Monty Python and the Holy Grail" (DISCLAIMER: we neither condone or dis-condone these movies, we're merely stating a fact. Like all other movies, you should make sure the ratings and material are to you and / or your parent / guardian's standards). It's an interpreted language. Computer programs are either compiled to machine code or interpreted by an interpreter. Compiled programs usually run faster, interpreted languages usually run slower. Examples of compiled languages are C and C++. Interpreted languages include python and Java. Another cool feature of python is that it's "dynamically typed". According to wikipedia, "A programming language is said to be dynamically typed when the majority of its type checking is performed at run-time as opposed to at compile-time. In dynamic typing, values have types but variables do not; that is, a variable can refer to a value of any type."1 This might not make much sense now, but we'll see it in action later on when we talk about variables in Lesson 3. Python, is well-known for being an easy language to learn. Personally, I think it's one of the best languages to start with, because of its simplicity. How about we jump right in to the code now? 1. http://en.wikipedia.org/wiki/Type_system#Dynamic_typing Summer Enrichment Program Lesson 1. My First Python Program Now that you know a little about the background of python, let's start with a simple python program. Step 0. Open Python Shell by going Start->All Programs->Python 2.5->IDLE (Python GUI). A window should open with a white background and some black text that reads something like: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 >>> Step 1. Python commands can now be typed into the Python Shell. The interpreter in Python Shell will compile and run those lines of code interactively. Try typing the following command: print "hello" Step 2. What happens? hello should be printed to the screen. The print command just prints anything you tell it to print. Try printing your own messages to the screen. Make sure to include the quotes around your message (explanation to follow). It could be anything like: print "I like pizza" Summer Enrichment Program print "how are you?" print "my favorite movie is avatar" Lesson 2. Data Types Integers and Floats Now to explain the quotes around your message as seen above. We place quotes around the message to let python know that those characters are a string. This is not the kind of string your cat plays with; it's a data type. OK, but what's a data type? The Wiktionary definition for data type is "a classification or category of various types of data, that states the possible values that can be taken, ... and what range of operations are allowed on them".2 In other words, a data type gives meaning to a piece of data in a computer program. If I asked you what 1 is, you would probably say it's a number, correct? Saying that 1 is a number is similar to giving data in a computer program a type. Number is the data type of 1. Let's see how this applies to the Wiktionary definition: "states the possible values that can be taken" - what are the possible values of a number? answer: negative infinity to infinity "what range of operations are allowed on them" - what operations can be performed on numbers? answer: addition, subtraction, division, multiplication, etc. Python has a couple numerical data type; one is called Integer. Integers can be added, subtracted, divided, multiplied, etc. Let's take a look at this in the Python Shell. Step 0. If you haven't already, open a Python Shell. 2. http://en.wiktionary.org/wiki/data_type Summer Enrichment Program Step 1. Enter the following command and press enter: type(1) What happens? <type 'int'> is displayed. This is telling you that 1 is of the type 'int'. 'int' is short for integer. Pretty cool! Step 2. Now try adding 2 integers. Type this and press enter: 1+3 You should see 4 appear on the line below. Now try some other operations. You can subtract (-), divide (/), and multiply (*). Here are some examples: 200-12 4/2 78*2 6+7+8 12/4*5 3/2 Integer isn't the only numerical data type; another is called float. Floats are very similar to integers. The main difference is that they include a decimal point, which allows for more precision. Floats can be added, subtracted, divided, and multiplied just like integers. Step 3. Try these in the Python Shell: 41.4+2 145.3-234.5 56*1.2 Summer Enrichment Program 3.0/2 If you're wondering why some of the answers might not be exactly right (they might look like this: 43.399999999999999), this is because the decimal point numbers are stored as approximations. Please see the python documentation for a more thorough explanation (http://docs.python.org/tutorial/floatingpoint.html). Strings Strings are another data type. Can you figure out what Strings are? They are basically any text. Like in the message you printed in Lesson 1, strings are surrounded by quotes. Python is pretty relaxed about the type of quotes, you can use either double quotes (") or single quotes ('). I'll use them both in the exercises from now on. Let's try playing with strings in the Python Shell! Step 0. What does python say is the type of "hello"? Use type() again to see what the type of "hello" is: type("hello") What does it say? 'str', short for string. Step 1. Enter a print statement again to print a message. It can be something like this: print "hello again!" Step 2. Can arithmetic operations be performed on strings, too? Can they be added, multiplied, subtracted, or divided? Try the following operations and see what happens: "this" + "that" "this" - "that" "this" * "that" Summer Enrichment Program "this" / "that" The first one works just fine. It outputs the string "thisthat". Makes sense, right? You might want to create a larger string from smaller strings in your computer program. For example, you might want to add "Hello, " plus a person's name if you wanted to greet a user to your website. The other operations fail with an error message. This also makes sense. Could you even imagine how "this" - "that" would work?? Step 3. Let's try to be a little sneaky, and see what happens when we enter the following commands (make sure to include the quotes!): "2" + "5" "4" - "7" "12" * "56" "18" / "4" The same outcome as above! Only the first one works, giving the output "25". The others fail. So, even though these are numbers, python interprets them as strings because of the quotes. Step 4. We can be even sneakier and change the type of those strings to an integer. How to do this, you ask? Simply, convert them to an integer by using the int() method (more about methods later.. don't worry about this word yet). Try this at the command line: int("2") * int("4") What happens? 8 should be printed! Sweet. Data can be changed from one type to another. Summer Enrichment Program Step 5. Let's try the reverse, converting an integer to a string. Type this into the Python Shell: str(5) + str(7) Can you guess what will be printed? Lesson 3. Variables The word variable is typically used as an adjective to describe something changes. For example, if the weather is variable, that might mean it's cloudy one minute and sunny the next. But what is a variable in computer programming? Here's the Wikipedia definition of a programming variable: "a variable is a facility for storing data. The current value of the variable is the data actually stored in the variable. Depending on the programming language in question, the data stored in the variable can be intentionally altered during the program run, thus causing its value to change, or vary, hence the name."3 Maybe this isn't completely clear, but hopefully it will make sense after some analogies and examples. You've probably already learned something similar to variables. Have you taken algebra? Remember problems like 4x + 2 = 14, where you need to solve for x? x is like a variable! x has a value, it's storing the data 3 in the equation (4*3 + 2 = 14). In computer programming, we're usually more explicit in naming our variables. We can use any letters, numbers, or an underscore, to name our variables. So, instead of x, we might want to have a variable called tip_percentage or taxrate2 or firstName. Then we 3. http://en.wikipedia.org/wiki/Variable_%28programming%29 Summer Enrichment Program assign a value to this variable. The value can be of any data type. Let's see this in practice: Step 0. If you haven't done so already, open a Python Shell. Step 1. Type the following lines into the command line: num = 3 print num This might not seem very interesting, but it is! The variable, num, is being assigned the integer value 3. The print command is printing the value. What can we do with this? Step 2. Let's try adding our variable num to another integer. Type the following into the command line: num + 4 What happens? 7 should be printed! The python interpreter is using the integer value of 3 for the variable num and is adding it to 4, which it calculates as 7. Step 3. What if we created another variable, let's say num1 and assigned that a value. Could we then add num and num1? Try these commands: num1 = 5 num + num1 You should see 8 printed to the screen. Step 4. OK, now let's test the "variable" aspect of variables. The Wikipedia definition says that variables are named "variable" because the values can be changed. Try assigning a different value to num: Summer Enrichment Program num = 10 print num num is now 10. Sweet, variables really are variable. Step 5. This doesn't seem too useful yet, but let's begin a little example that will help you realize how powerful this can be. It will be called "Gift Card Example", I'll refer to it as such in the future. Our end goal is to allow a user to enter an amount of a gift card they were given and find out whether the total cost of an item(s) they want to buy is less than their gift card value. To begin our example, see if you can create 2 variables, one called cost with a value of 12, the other called sales_tax_rate with a value of .095. Now multiply cost * sales_tax_rate. What does that give you? Here's what the code should look like: cost = 12 sales_tax_rate = .095 cost * sales_tax_rate This gives you the amount of tax you would have to pay on an item that cost $12. Assign this to another variable, called tax, by doing the following: tax = cost * sales_tax_rate print tax Great, now we have the amount of tax saved in a variable called tax. Can you figure out how to save the total cost (including tax) of the item to a variable and then print that variable? Give it a try. The solution is in Appendix A (Solution 0). OK, great! We'll come back to this exercise later! Step 6. Let's not forget about our other data type, strings! Variables can also be used to Summer Enrichment Program store string data. Try these commands: fname = "bob" lname = "wright" fname + lname fname = "sue" print fname Step 7. Remember dynamic typing from the introduction? Python is said to be a dynamically typed language because variables can be assigned different types throughout the execution of the program. What does this mean? Well, you can start by assigning a variable an integer value, then later change this to a string value, and finally change it to a float value. Try this in the Python Shell: dvar = 12 type(dvar) dvar = "string" type(dvar) dvar = 4.5 type(dvar) See how the type changes as you assign different values? This isn't possible in some other languages, such as Java. There would be a error if you tried assigning an integer value to a variable that has been declared to hold a string. OK, moving on to data structures... Summer Enrichment Program Lesson 4. Data Structures Lists Data structures allow a programmer to group together sets of data in a logical manner. Python has a few data structures; the 2 that we'll go over are lists and dictionaries. First, lists. How do you use lists in your own life? Personally, I use lists to keep track of the groceries I need to buy at the store or the tasks I need to do during the day. Lists could be related to TV: for example, there is a list of the channels that you get on your cable or what shows are going to on at 8pm on Tues. We use lists very often in real life; it makes sense to use them in computer programming, too! In the Facebook code, a list might be used to store all your friends. Or the code on your TiVo might use a list to save a list of all the TV shows on CBS. Can you think of how other applications might use a list? In python, a list is represented by square brackets ([]). Let's try creating a new list: Step 0. Open a Python Shell as usual. Step 1. At the command line, type the following: tvshows = [] Great! We now have a variable, tvshows, that is a list data type. (You can verify this by using type(tvshows).) But our TV show list is empty right now, which isn't very useful. Let's add some TV shows to our list. Step 2. To add data to our list, you need to use the append method of the list class. OK, what? What's a method? What's a class? Both methods and classes are a way to modularize code, making the code better organized and reusable. Methods are a way of Summer Enrichment Program grouping code together to perform a single action. For example, you might create a method to take 2 numbers and return the sum of the numbers. The append method adds data to the end of a list. If you think of a method as a way of grouping code together to perform a single action, then you can think of a class as a way of grouping methods and variables together to perform many actions that are all related in some way. Classes in programming can sometimes relate to real world objects. The classic example is a bank account (a little boring, yes, but it's easy to visualize). In your bank account class, you would have a variable for the total amount of money in the account. Then you could add methods such as deposit(money) or withdraw(money) that add or subtract money from the total amount. If you're interested in learning more about methods and classes, I strongly encourage you to read the python documentation (methods, aka functions http://docs.python.org/tutorial/controlflow.html#defining-functions and classes http://docs.python.org/tutorial/classes.html). Back to our lists! We wanted to add data to our tvshows list. To do so, enter the following code into the command line: tvshows.append("CSI Miami") This adds "CSI Miami" to our list. How can we be sure? Step 3. Print the list to make sure the data was really added: print tvshows Yup, CSI Miami was added to the list. Try adding some more TV shows to the list! Step 4. Like many things you'll find in programming, there is often more than one way Summer Enrichment Program to accomplish a task. We could create a new list and add the values in one step. Try typing the following lines into the Python Shell to see what happens: moretvshows = ["24", "The Office", "SpongeBob"] print moretvshows Step 5. There are some cool things you can do with lists. For one, you can print the length. To do so, use the len method to get the length of the list: len(tvshows) Step 6. You can also access single items in the list. Let's say you wanted to access just the 1st element to change it's value: tvshows[0] = "30 Rock" You might be saying: wait, that's a zero, not 1! Why is zero used to access the first element instead of 1? In computer programming, someone decided a long time ago to start counting at 0 rather than 1. So, the "index" of our list starts with 0, 1, 2... To access the second element, use 1 as the index: tvshows[1] = "American Idol" What happens if you use a really, really large index that is definitely bigger than our list? Give it a try: tvshows[100000] An error! Step 7. Python has a really cool feature that allows you easy access to the last element in the list. You can use -1 as the index. Example: Summer Enrichment Program tvshows[-1] What happens when you type this? It should display the last item in your list! It might not seem very useful now, but trust me, I've used it several times in some complex programs! Step 8. Lastly, you can sort lists. This can be extremely useful. Try this code in the Python Shell: numbers = [4, 3, 5, 1, 2] numbers.sort() print numbers The numbers in the list are now sorted! This will also work on lists of strings, putting the strings in alphabetical order. Dictionaries OK, those are the basics of lists. Now let's go over dictionaries. Like lists, we often use dictionaries in real life. A good example: the dictionary. :) Think about the dictionary for a second. What is it doing? It's actually acting like a python dictionary on 2 levels. First, it groups all the words that start with a certain letter into different sections. If I said to you, give me all the words that start with A, you would open the dictionary, turn to the page that A starts on, and start reading the words. Not only does it do this, but it also maps a word to its definition(s). If I asked you for the definition of the word "tangerine", you would be able to look up tangerine and give me the definition. What's common in these 2 functions? I ask for something by giving you a letter or a word (ie, a key), and you give me back something that relates to that key (ie, a value for that key). The dictionary is mapping keys to values. Can you think of anything else in real life that acts like a dictionary? I can think of a couple: an encyclopedia or a phone book. Summer Enrichment Program Since we use dictionaries in real life, it makes sense to have them in computer programming, too (like lists!). Going back to Facebook, Facebook might want to use a dictionary to map a person's name to their friends. Netflix might use a dictionary to map a user to their queue of movies. The contact list on your cell phone might map your friends' names to their phone number. Let's see how this works in python. In python, the dictionary is represented as curly brackets ({}). Let's create a dictionary mapping names to phone numbers: Step 0. Create a new dictionary: phone_book = {} And that's it! We have our new dictionary. Let's add some names and phone numbers to our phone book. Step 1. Add a name that maps to the person's phone number: phone_book['Bob'] = '415-555-1203' Does this notation look somewhat familiar? Maybe similar to the lists we learned about earlier? That's cuz it's identical. Yea. One less thing to remember! Lists are just dictionaries with integers as keys. Step 2. Now that we have Bob in our address book, let's say you want to get his phone number. You can do so like this: print phone_book['Bob'] Or, you might have noticed that Bob is just a string, and strings can be saved in variables, so we could even do something like this: Summer Enrichment Program name = "Bob" print phone_book[name] Step 3. Add some more people and phone numbers to the phone_book dictionary. When done, use the command print phone_book to verify the names and phone numbers have been added properly. Step 4. Now let's change Bob's phone number. How do you think you would do this? Try it yourself, the solution is in Appendix A (Solution 1). Step 5. Similar to lists, dictionaries can be created in one step: phone_book2 = { "Bob":"407.555.2341", "Susan":"302.555.4212", "Kelly":"302.555.4521" } Note the syntax: { key:value, key:value ... } Step 6. There are some cool things you can do with dictionaries. For example, you can get a list of all the keys. Try this: phone_book.keys() Or you can get a list of all the values. Try this: phone_book.values() Step 7. What if you wanted to combine lists and dictionaries?? So far, we've only been using strings as the values, but the values can be integers, dictionaries, floats, even other dictionaries! Going back to our TV example, what if we wanted to map a list of tv shows to a channel? For example, we could map the channel CBS to a list of shows on CBS. See if you can figure the code out on your own first. (Some shows on CBS are "CSI", "The Summer Enrichment Program Good Wife" and "The Price is Right". Some shows on ABC are "Desperate Housewives" and "20/20".) If you need help, one possible answer is in Appendix A (Solution 2)! Lesson 5. If Statements "OK, great," you might say, "I can create variables. I can perform arithmetic. But this isn't very interesting. What if I want to take some data and print a message based on the data? Or what if I want to perform a task for every item in a list or dictionary?" Given what you know so far, this would be very tricky. Let's take your first question: "What if I want to take some data and print a message based on the data?" For example, you might want to print a simple message such as "Hot" or "Cold" based on a temperature reading. Or you might want to print "Good morning" or "Good evening" based on the time of day. Let's take the first example. You could think of it this way: given the current temperature, if the temperature is greater than or equal to 80 degrees, then print "Hot". Otherwise, print "Cold". I'll write this in another way: temperature = 80 if temperature >= 80: print "Hot" else: print "Cold" Guess what, that's python code! This is called an "if statement". There are a couple important things to know about if statements. First, you should know the general structure. Then you should know how they work. Let's just look at the structure first. Summer Enrichment Program Structure In the if statement above, there are 2 blocks of code. One block is under the if statement, the other block is under the else statement. Notice that the code blocks are indented. I used a tab here, but you could also use spaces. The important thing is that all lines of code in the same code block are indented the exact same amount. This leads me to my next point... In the example above, each block has only 1 line of code, but that's not always the case. There could be several lines of code in each block. Here's an example: if temperature >= 80: temperature = 80 print "Hot" else: temperature = 79 print "Cold" Like I mentioned earlier, all code in the block needs to be indented the same amount. One final thing note about the structure: you need to place a colon (:) after the if statement and the else statement. Look at the code again. if temperature >= 80: #<- colon here print "Hot" else: #<- colon here print "Cold" See the colons? If you don't include these, there will be an error when you try to run your code. The colons tell python that the if and else statements are over and the next lines of code are the code blocks. Summer Enrichment Program Step 0. Now that you know the structure, try entering the following code into the Python Shell. temperature = 80 if temperature >= 80: print "Hot" else: print "Cold" You might notice that after you enter the if statement line, three dots appear (...). That's normal. Also, remember to indent the lines in the code blocks. Finally, hit the enter key twice after you're done typing the last line. What is the output? It should say Hot. Here's a screen shot of what it looks like: How If Statements Work The code after the word if (temperature >= 80) is called a boolean expression. Huh? Boolean expression is a really strange term. Basically, it means that the expression is either true or false. You can use the following comparison operators to form a boolean expression: ==, !=, <, <=, >=, >. Most of these are straight forward, except for maybe the == and != comparison operators. Can you guess what == does? It checks if one piece of data is equal to another. Why not just use 1 equal sign instead of 2, you might ask? Good question. Python already uses one equal sign to mean "assignment". In other words, if you wrote temperature = 80, python would think you're assigning the value 80 to the temperature variable. A different symbol has to be used for comparison, and Summer Enrichment Program that's ==. Now how about !=. Can you guess what this does? It means not equal to. For example, you might want to say "if the temperature is not equal to 80, do something interesting." Step 0. Here are some examples of boolean expressions, fill out their meaning (the first one is done for you as an example): name == "Bob" Meaning: name is equal to "Bob" price < 20 Meaning: grade >= 80 Meaning: temperature != -50 Meaning: Going back to the code above, the temperature variable is first set to 80. Then, python evaluates the boolean expression temperature >= 80. In this case it's true, which means runs the code block under the if statement and skips the code under the else statement. If it was false, it would run the code block under the else statement and skip the code under the if statement. There's actually one more type of statement that you can use: the elif statement. Any idea what this might stand for? else if. This gives us even more options for our if statements. Here's an example: Summer Enrichment Program temperature = 78 if temperature >= 80: print "Hot" elif temperature >=70: print "Just right" elif temperature >= 60: print "A little bit cold" else: print "Cold" The elif statement is placed between the if and else statements and includes a boolean expression like the if statement. You can add as many elif statements as you want! You could even have 1000 if you wanted! During the execution of the program, the boolean expression in the if statement is first tested. If it is true, the code block under the if statement is executed and the rest is skipped. If it is false, the boolean expression in the next elif statement is tested. If that boolean expression is true, the code in the code block will be executed and the rest is skipped. If none of the boolean expressions are true, only the code in the else statement is executed. Can you figure out the output of the code above? (Solution 3, Appendix A) What if the temperature was 66? (Solution 4, Appendix A) Let's try an example. Step 1. Open a Python Shell as usual. Step 2. Given the following if statement, what will be printed? weather = "raining" if weather == "sunny": print "Play tennis" elif weather == "cloudy: Summer Enrichment Program print "Go shopping" elif weather == "raining": print "See a movie" else: print "Not sure what to do!" Now test it yourself in the Python Shell. Step 3. Let's go back to our "Gift Card Example" that we started earlier. If you don't remember, here's the code: cost = 12 sales_tax_rate = .095 tax = cost * sales_tax_rate total_cost = tax + cost print total_cost This code finds the total cost of an item, given the sales tax. Our end goal is to allow a user to enter in an amount of a gift card and find out whether the total cost of an item(s) they want to buy is less than their gift card value. So far we have just the cost of an item. Before we do anything else, let's move this code to a file so we don't have to keep typing it over and over again. Open a new window by going File->New Window in Python Shell, and write the code into the file. Save the file as giftcard.py, and save it directly to My Documents. You can run the code in the file by opening it (File->Open) and clicking on Run->Run Module. In your Python Shell, you will see the result as below: >>> ================================ RESTART ================================ >>> 13.14 Summer Enrichment Program Step 4. Now that our code is in a file, we'll add 2 more pieces to our code: adding a gift card value and printing a message letting the user know if they've gone over the gift card amount. Let's start with the first piece: adding a gift card value. This is fairly simple, just add another variable at the very top of your code called "gift_card_value" and make this equal to whatever value you'd like. gift_card_value = 20 Step 5. Now, try to figure out how to use an if statement to print a message that says "Over budget" if the user wants to buy something that costs more than the gift card value. If they're under budget, print a message that says "OK". Then print how much money the person has left. (See Appendix A, Solution 5 for one possible solution) Lesson 6. Loops For loops Remember the other problem we wanted to solve earlier: what if we wanted to loop through every item in a list and perform some operation on the value? For example, let's say we had a list of names, maybe all your friends on Facebook, and we wanted to print out all their names. You could say it like this: for each friend in my friend list, print the person's name. I'll write it one more way: friends = ['Stephanie', 'Amy', 'Candice', 'Maggie'] for name in friends: print name Summer Enrichment Program Guess what! That's python code! This is called a for loop. The for loop loops through each item in the list and allows you to perform some operation on that item. In this example, our operation is to print the item. Look at the structure of this code. Similar to our if statements, there's a code block that's indented. Although this example has only one line of code in the block, there can be more than one line. Each line has to be indented the same amount. Also notice that there's another colon at the end, just like the if statements! Here's a more complex example. Let's say we wanted to create a website that found the best deals on clothes by "scraping" other sites for pricing information. For example, we might scrape macys.com and nordstrom.com for the price of a pair of Guess jeans. We would first save the links in a list. We could then open a connection to each link and get the contents of the page. We could have a certain pattern we might want to match on the page, maybe something like $number.number, and save any content that matches that pattern for later use. Here's what the code might look like (don't worry if you don't understand it all, just notice that it uses a for loop!): urls = ["http://www.macys.com/product/3214", "http://www.nordstrom.com/ product/425", "http://www.jcpenney.com/product/id=452"] for url in urls: page_contents = open(url).read() matches = re.search("(\$\d+\.\d{2})", page_contents) match = Match(url=url, matches=matches) match.save() Let's try some examples! Step 0. Open the Python Shell. Step 1. Enter the following code and hit Enter twice: Summer Enrichment Program for i in range(5): print i What happens when you run the code? This should be printed: 0 1 2 3 4 Step 2. Why does the previous code print 0 to 4? To answer that question, try typing this into the Python Shell: print range(5) What is printed? [0, 1, 2, 3, 4]. What does that look like? If you guessed a list, you would be correct! The range method is creating a list of integers from 0 to 4. The list starts at 0, then ends at the number before 5. If you tried range(10), can you guess what list would be created? Step 3. Let's try another example. Type this code into the Python Shell to see what it does: phone_numbers = { "Anna":"415-555-1234", "James":"650-555-1524", "Mike":"408-555-1234" } for name in phone_numbers.keys(): print phone_numbers[name] Remember that the keys() method retrieves a list of all the keys in the dictionary. The loop then loops through all the keys and uses the key to print associated phone number. Summer Enrichment Program Step 4. Your turn! Write code to do the following: for each number in the range 0 to 9, print the result of that number times itself. (See Appendix A, Solution 6 for one possible solution) While loops There's another type of loop available in python: while loops. The basic idea behind a while loop is that the loop keeps running the code block while something is true and stops once it become false. For example, you might want to build a music player that keeps playing music while the user has not pressed the stop button. Once the user presses the stop button, the program stops playing the music. Here's a simple example of a while loop: counter = 1 while counter < 10: print counter counter = counter + 1 What does this code do? It keeps printing the counter value until the counter is no longer less than 10. While loops have a boolean expression, just like if statements. In this example, why does the counter value increase? Because you keep adding 1 every time you loop (line 4). What would happen if you didn't add one to the counter or did something like this: counter = 1 while counter < 10: print counter counter = 1 Summer Enrichment Program This will run forever! We call this an infinite loop. Sometimes you might want to use an infinite loop, but most often you don't. :) An infinite loop could also be written like this: while True: print 'hi' Time to practice. Step 0. Open the Python Shell if you haven't done so already. Step 1. Try this code for yourself: counter = 1 while counter < 10: print counter counter = counter + 1 Does it work like you expected? Step 2. Now try an infinite loop. To stop the program, you'll have to hit CTRL-C. while True: print 'hi' Step 3. Write a while loop that prints the numbers 0 to 4 then stops. (See Appendix A, Solution 7 for one possible solution) Remember you did something like this with a for loop? Often what can be accomplished with a for loop can also be accomplished with a while loop! Step 4. Let's finish up the Gift Card Example we were working on earlier. Here's the code you should have so far in your giftcard.py file (if it's not the same, take a moment to change it to match): Summer Enrichment Program gift_card_value = 20 cost = 12 sales_tax_rate = .095 tax = cost * sales_tax_rate total_cost = tax + cost print total_cost left_over = gift_card_value - total_cost if left_over < 0: print "Over budget" else: print "OK" print left_over Let's make some really cool changes. First, we'll get input from the user rather than 'hard-coding' the gift card value and item cost. To get input from the user, you can use the input method. It looks sometime like this: gift_card_value = int(raw_input('Enter the amount of your gift card: ')) cost = int(raw_input('Enter the amount of the item: ')) Try adding these lines to the program, replacing the first 2 lines. Run the program to see what happens. Step 5. How about we let the user input the cost of several items instead of just one? We can let them keep entering the cost of items until they enter the character 'q'. Sounds like we might want to use a loop to solve this problem, huh? We would want cost to represent the entire cost of all the items, adding each item's cost to this value as the user enters it. Once the user enters 'q', the program would stop asking for input from the user and then continue with the rest of the calculations. Here are the steps: Summer Enrichment Program get the gift card value set the cost variable to zero get the item_cost from the user (Hint: item_cost = raw_input("Enter a cost: ")) while the item_cost is not equal to 'q' add the item_cost to the cost (Hint: cost = cost + int(item_cost)) get the item_cost from the user again ...continue with the rest of the program Try to translate these steps to python code. (See Appendix A, Solution 8 for one possible solution) Appendix A. Solutions Solution 0. total_cost = cost + tax print total_cost Solution 1. phone_book['Bob'] = '415-555-6123' Solution 2. tv = {"CBS":["CSI", "The Good Wife", "The Price is Right"],"ABC":["Desperate Housewives", "20/20"]} Solution 3. Just right Summer Enrichment Program Solution 4. A little bit cold Solution 5. gift_card_value = 20 cost = 12 sales_tax_rate = .095 tax = cost * sales_tax_rate total_cost = tax + cost print total_cost left_over = gift_card_value - total_cost if left_over < 0: print "Over budget" else: print "OK" print left_over Solution 6. for i in range(10): print i*i Solution 7. counter = 0 while counter < 5: print counter counter = counter + 1 Solution 8. Summer Enrichment Program gift_card_value = int(raw_input('Enter the amount of your gift card: ')) item_cost = raw_input('Enter the amount of the item (Enter q to stop): ') cost = 0 while item_cost != 'q': cost = cost + int(item_cost) item_cost = raw_input('Enter the amount of the item (Enter q to stop): ') sales_tax_rate = .095 tax = cost * sales_tax_rate total_cost = tax + cost print total_cost left_over = gift_card_value - total_cost if left_over < 0: print "Over budget" else: print "OK" print left_over