12.07.2015 Views

Python for CS4SF - Computer Science

Python for CS4SF - Computer Science

Python for CS4SF - Computer Science

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Python</strong> <strong>for</strong> Beginners<strong>Python</strong> <strong>for</strong> Beginners.................................................................................1Lesson 0. A Short Intro................................................................................................. 2Lesson 1. My First <strong>Python</strong> Program ............................................................................. 2Lesson 2. Input from user............................................................................................. 3Lesson 3. Variables ....................................................................................................... 3Lesson 4. If Statements................................................................................................. 5Structure.................................................................................................................... 6How If Statements Work .......................................................................................... 7Lesson 5. Simple Loops ................................................................................................ 9Lesson 6. Data Types .................................................................................................. 10Integers and Floats.................................................................................................. 10Strings ..................................................................................................................... 12Lesson 7. Data Structures ........................................................................................... 14Lists ......................................................................................................................... 14Dictionaries ............................................................................................................. 16Lesson 8. Loops .......................................................................................................... 19For loops.................................................................................................................. 19While loops.............................................................................................................. 21Appendix A. Solutions ................................................................................................ 23


Lesson 0. A Short IntroFirst, 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.<strong>Python</strong>, is well-known <strong>for</strong> being an easy language to learn.Lesson 1. My First <strong>Python</strong> ProgramLet's start with a simple python program.Step 0. Open <strong>Python</strong> Shell by going Start (Windows logo at the bottom left) ->AllPrograms-><strong>Python</strong> 2.7->IDLE (<strong>Python</strong> GUI). A window should open with a whitebackground and some black text that reads something like:<strong>Python</strong> 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit(Intel)] on win32Type "copyright", "credits" or "license()" <strong>for</strong> more in<strong>for</strong>mation.****************************************************************Personal firewall software may warn about the connection IDLEmakes to its subprocess using this computer's internal loopbackinterface. This connection is not visible on any externalinterface and no data is sent to or received from the Internet.****************************************************************IDLE 1.2.2>>>Step 1. <strong>Python</strong> commands can now be typed into the <strong>Python</strong> Shell. The interpreterin <strong>Python</strong> Shell will compile and run those lines of code interactively. Try typing thefollowing command:print "Alice in Wonderland"Step 2. What happens? Alice in Wonderland should be printed to the screen. Theprint command just prints anything you tell it to print. Try printing your ownmessages to the screen. Make sure to include the quotes around your message(explanation to follow). It could be anything like:print "Oh dear! Oh dear! I shall be too late!"print "DRINK ME"print "EAT ME"


Lesson 2. Input from userNow your program can print all the things the white rabbit says, the bottle says, andthe cookie says. How about what YOU want to tell the program?Step 0. If you haven't done so already, open a <strong>Python</strong> Shell.Step 1. Type the following line into the command line:print raw_input("Enter 1 if you want to drink me, 2 if you don't: ")Step 2. What did your program say? It should have showedEnter 1 if you want to drink me, 2 if you don't:Step 3. Answer with 1 or 2. What happens?Lesson 3. VariablesNow we can get the input from user, but <strong>for</strong> more fun, we want "react" to what userhas said. For example, if the user said 1, then we want to shrink Alice! To do so, yourprogram needs to remember what the user said. A computer program remembers bystoring what user has said in a "variable".You've probably already learned something similar to variables. Have you takenalgebra? Remember problems like 4x + 2 = 14, where you need to solve <strong>for</strong> x? x is likea 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. Wecan use any letters, numbers, or an underscore, to name our variables. So, instead ofx, we might want to have a variable called answer or rabbit or firstName. Then weassign a value to this variable. The value can be of any data type. Let's see this inpractice:Step 0. If you haven't done so already, open a <strong>Python</strong> Shell.Step 1. Type the following lines into the command line:


firstName = "Alice"print firstNameThis might not seem very interesting, but it is! The variable, firstName, is beingassigned "Alice". The quotation marks around Alice means that this is a String - atext. The print command is printing the value, what's inside of the variablefirstName. What can we do with this?Step 2. Let's try adding the last name to the first name. Type the following into thecommand line:firstName + " Lewis"What happens? 'Alice Lewis' should be printed! The single quotation marks meanthat <strong>Python</strong> understands that Alice Lewis is a text. The python interpreter is usingthe value of "Alice" <strong>for</strong> the variable firstName and is adding " Lewis" to "Alice", whichturns out to be a new text "Alice Lewis".Step 3. What if we created another variable, let's say lastName and assigned that avalue. Could we then add firstName and lastName? Try these commands:lastName = "Lewis"firstName + " " + lastNameYou should see 'Alice Lewis' printed to the screen.Step 4. OK, now let's test the "variable" aspect of variables. The Wikipedia definitionsays that variables are named "variable" because the values can be changed. Tryassigning a different value to firstName:firstName = "Carol"print firstNamefirstName is now 'Carol'. Sweet, variables really are variable.Step 5. This doesn't seem too useful yet, but let's begin a little example that will helpyou realize how powerful this can be. It will be called "Knock Knock Joke". Yourprogram will play the knock knock joke with you. Your program will start by saying"Knock Knock", and then the program will ask "Who's there?". To begin our example,


see if you can create a variable, called name. Now can you make your program to saythe name and "who?" Here's what the beginning of the code should look like:print "Knock Knock"name = raw_input("Who's there? ")This assigns whatever name you typed to the variable name. You can print name tosee if it has the correct name.print nameGreat, now we have the name you typed. Can you figure out how to print "who?" afterthe name? (Solution 1 in Appendix A)Be<strong>for</strong>e we do anything else, let's move this code to a file so we don't have to keeptyping it over and over again. Open a new window by going File->New Window in<strong>Python</strong> Shell, and write the code into the file. Save the file as knockknock.py, andsave 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 <strong>Python</strong> Shell, you will see theresult as below:>>> ================================ RESTART================================>>>Knock KnockWho's there?Lesson 4. If Statements"OK, great," you might say, "I can create variables. I can do knock knock jokes. Butthis isn't very interesting. How does my program shrink Alice when the user says 1?"Let's take your Alice question: "What if I want to take a number and print a messagebased on the number?" For example, you might want to print a simple message suchas "Alice shrank!" or "A white rabbit just passed!" based on the number. You couldthink of it this way: given the answer from the user, if the number is 1 ("Drink me"),then print "Alice shrank!". Otherwise, print "Alice grew taller!". I'll write this inanother way:


answer = raw_input("Enter 1 if you want to drink me, 2 if you don't: ")if answer == "1":print "Alice shrank!"else:print "A white rabbit just passed!"Guess what, that's python code! This is called an "if statement". There are a coupleimportant things to know about if statements. First, you should know the generalstructure. Then you should know how they work. Let's just look at the structure first.StructureIn the if statement above, there are 2 blocks of code. One block is under the ifstatement, the other block is under the else statement. Notice that the code blocksare indented. I used a tab here, but you could also use spaces. The important thing isthat 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 thecase. There could be several lines of code in each block. Here's an example:if temperature >= 80:temperature = 80print "Hot"else:temperature = 79print "Cold"Like I mentioned earlier, all code in the block needs to be indented the sameamount.One final thing note about the structure: you need to place a colon (:) after the ifstatement and the else statement. Look at the code again.if temperature >= 80:print "Hot"else: #


See the colons? If you don't include these, there will be an error when you try to runyour code. The colons tell python that the if and else statements are over and the nextlines of code are the code blocks.Step 0. Now that you know the structure, try entering the following code into the<strong>Python</strong> Shell.temperature = 80if 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 theenter key twice after you're done typing the last line. What is the output? It shouldsay Hot. Here's a screen shot of what it looks like:How If Statements WorkThe 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 iseither true or false. You can use the following comparison operators to <strong>for</strong>m aboolean expression: ==, !=, . Most of these are straight <strong>for</strong>ward, except<strong>for</strong> maybe the == and != comparison operators. Can you guess what == does? Itchecks if one piece of data is equal to another. Why not just use 1 equal sign insteadof 2, you might ask? Good question. <strong>Python</strong> already uses one equal sign to mean"assignment". In other words, if you wrote temperature = 80, python would thinkyou're assigning the value 80 to the temperature variable. A different symbol has tobe used <strong>for</strong> comparison, and that's ==.Now how about !=. Can you guess what this does? It means not equal to. Forexample, you might want to say "if the temperature is not equal to 80, do somethinginteresting."


Step 0. Here are some examples of boolean expressions, fill out their meaning (thefirst one is done <strong>for</strong> you as an example):name == "Alice"Meaning: name is equal to "Alice"price < 20Meaning:grade >= 80Meaning:temperature != -50Meaning: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 theelse statement. If it was false, it would run the code block under the else statementand skip the code under the if statement.There's actually one more type of statement that you can use: the elif statement. Anyidea what this might stand <strong>for</strong>? else if. This gives us even more options <strong>for</strong> our ifstatements. Here's an example:temperature = 78if 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 aboolean expression like the if statement. You can add as many elif statements as youwant! 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 blockunder 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, thecode in the code block will be executed and the rest is skipped. If none of the booleanexpressions are true, only the code in the else statement is executed. Can you figureout the output of the code above? (Solution 2, Appendix A) What if the temperaturewas 66? (Solution 3, Appendix A)Let's try an example.Step 1. Open a <strong>Python</strong> Shell as usual.Step 2. Given the following if statement, what will happen?weather = raw_input("How's the weather today? ")if weather == "sunny":print "Play tennis"elif weather == "cloudy:print "Go shopping"elif weather == "raining":print "See a movie"else:print "Not sure what to do!"Now test it yourself in the <strong>Python</strong> Shell.Lesson 5. Simple LoopsImagine that you have to do the same thing over and over again. It would be tiringand boring, right? <strong>Computer</strong>s are perfect <strong>for</strong> doing the repetition <strong>for</strong> you. Let's startwith printing the same thing multiple times.Step 1. Given the following print statement, what will happen?print "*"*5Step 2. Try the following range statement, what happens?range (1,5)Step 3. Let's print a triangle. Try with different ranges to make different triangles.


<strong>for</strong> i in range (1,5):... print "*"*i...**********Step 4. Can you print a triangle like this?**********Step 5. Challenge! Can you print a triangle like this?****************Lesson 6. Data TypesIntegers and FloatsNow to explain the quotes around your message as seen above. We place quotesaround the message to let python know that those characters are a string. This is notthe kind of string your cat plays with; it's a data type. OK, but what's a data type? TheWiktionary definition <strong>for</strong> data type is "a classification or category of various types ofdata, that states the possible values that can be taken, ... and what range ofoperations are allowed on them". 1 In other words, a data type gives meaning to apiece of data in a computer program. If I asked you what 1 is, you would probably sayit's a number, correct? Saying that 1 is a number is similar to giving data in acomputer program a type. Number is the data type of 1. Let's see how this applies tothe Wiktionary definition:1. http://en.wiktionary.org/wiki/data_type


"states the possible values that can be taken" - what are the possible values of anumber?answer: negative infinity to infinity"what range of operations are allowed on them" - what operations can be per<strong>for</strong>medon numbers?answer: addition, subtraction, division, multiplication, etc.<strong>Python</strong> has a couple numerical data type; one is called Integer. Integers can beadded, subtracted, divided, multiplied, etc. Let's take a look at this in the <strong>Python</strong>Shell.Step 0. If you haven't already, open a <strong>Python</strong> Shell.Step 1. Enter the following command and press enter:type(1)What happens? is displayed. This is telling you that 1 is of the type 'int'.'int' is short <strong>for</strong> integer. Pretty cool!Step 2. Now try adding 2 integers. Type this and press enter:1+3You should see 4 appear on the line below. Now try some other operations. You cansubtract (-), divide (/), and multiply (*). Here are some examples:200-124/278*26+7+812/4*53/2Integer isn't the only numerical data type; another is called float. Floats are verysimilar to integers. The main difference is that they include a decimal point, whichallows <strong>for</strong> more precision. Floats can be added, subtracted, divided, and multipliedjust like integers.Step 3. Try these in the <strong>Python</strong> Shell:


41.4+2145.3-234.556*1.23.0/2If you're wondering why some of the answers might not be exactly right (they mightlook like this: 43.399999999999999), this is because the decimal point numbers arestored as approximations. Please see the python documentation <strong>for</strong> a more thoroughexplanation (http://docs.python.org/tutorial/floatingpoint.html).StringsStrings are another data type. Can you figure out what Strings are? They are basicallyany text. Like in the message you printed in Lesson 1, strings are surrounded byquotes. <strong>Python</strong> is pretty relaxed about the type of quotes, you can use either doublequotes (") or single quotes ('). I'll use them both in the exercises from now on. Let'stry playing with strings in the <strong>Python</strong> Shell!Step 0. What does python say is the type of "hello"? Use type() again to see what thetype of "hello" is:type("hello")What does it say? 'str', short <strong>for</strong> string.Step 1. Enter a print statement again to print a message. It can be something likethis:print "hello again!"Step 2. Can arithmetic operations be per<strong>for</strong>med on strings, too? Can they be added,multiplied, subtracted, or divided? Try the following operations and see whathappens:"this" + "that""this" - "that""this" * "that""this" / "that"The first one works just fine. It outputs the string "thisthat". Makes sense, right? Youmight 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 togreet a user to your website.The other operations fail with an error message. This also makes sense. Could youeven imagine how "this" - "that" would work??Step 3. Let's try to be a little sneaky, and see what happens when we enter thefollowing 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". Theothers fail. So, even though these are numbers, python interprets them as stringsbecause 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 thecommand line:int("2") * int("4")What happens? 8 should be printed! Sweet. Data can be changed from one type toanother.Step 5. Let's try the reverse, converting an integer to a string. Type this into the<strong>Python</strong> Shell:str(5) + str(7)Can you guess what will be printed?OK, moving on to data structures...


Lesson 7. Data StructuresListsData structures allow a programmer to group together sets of data in a logicalmanner. <strong>Python</strong> has a few data structures; the 2 that we'll go over are lists anddictionaries.First, lists. How do you use lists in your own life? Personally, I use lists to keep trackof 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: <strong>for</strong> example, there is a list of the channels that you geton your cable or what shows are going to on at 8pm on Tues. We use lists very oftenin real life; it makes sense to use them in computer programming, too! In theFacebook code, a list might be used to store all your friends. Or the code on yourTiVo might use a list to save a list of all the TV shows on PBS. Can you think of howother 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 <strong>Python</strong> 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 thisby using type(tvshows).) But our TV show list is empty right now, which isn't veryuseful. 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 tomodularize code, making the code better organized and reusable. Methods are a wayof grouping code together to per<strong>for</strong>m a single action. For example, you might create amethod to take 2 numbers and return the sum of the numbers. The append methodadds data to the end of a list.If you think of a method as a way of grouping code together to per<strong>for</strong>m a singleaction, then you can think of a class as a way of grouping methods and variablestogether to per<strong>for</strong>m many actions that are all related in some way. Classes inprogramming can sometimes relate to real world objects. The classic example is a


ank account (a little boring, yes, but it's easy to visualize). In your bank accountclass, you would have a variable <strong>for</strong> the total amount of money in the account. Thenyou could add methods such as deposit(money) or withdraw(money) that add orsubtract money from the total amount. If you're interested in learning more aboutmethods 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 thefollowing code into the command line:tvshows.append("Curiosity Quest")This adds "Curiosity Quest" to our list. How can we be sure?Step 3. Print the list to make sure the data was really added:print tvshowsYup, Curiosity Quest was added to the list. Try adding some more TV shows to thelist!Step 4. Like many things you'll find in programming, there is often more than oneway to accomplish a task. We could create a new list and add the values in one step.Try typing the following lines into the <strong>Python</strong> Shell to see what happens:moretvshows = ["Arthur", "Angelina Ballerina", "WordGirl"]print moretvshowsStep 5. There are some cool things you can do with lists. For one, you can print thelength. 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 accessjust the 1st element to change it's value:tvshows[0] = "Martha Speaks"


You might be saying: wait, that's a zero, not 1! Why is zero used to access the firstelement instead of 1? In computer programming, someone decided a long time ago tostart counting at 0 rather than 1. So, the "index" of our list starts with 0, 1, 2... Toaccess the second element, use 1 as the index:tvshows[1] = "High School Musical"What happens if you use a really, really large index that is definitely bigger than ourlist? Give it a try:tvshows[100000]An error!Step 7. <strong>Python</strong> has a really cool feature that allows you easy access to the lastelement in the list. You can use -1 as the index. Example:tvshows[-1]What happens when you type this? It should display the last item in your list! Itmight not seem very useful now, but trust me, I've used it several times in somecomplex programs!Step 8. Lastly, you can sort lists. This can be extremely useful. Try this code in the<strong>Python</strong> Shell:numbers = [4, 3, 5, 1, 2]numbers.sort()print numbersThe numbers in the list are now sorted! This will also work on lists of strings, puttingthe strings in alphabetical order.DictionariesOK, those are the basics of lists. Now let's go over dictionaries. Like lists, we often usedictionaries in real life. A good example: the dictionary. :) Think about the dictionary<strong>for</strong> 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 Isaid 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 <strong>for</strong> the definition of theword "tangerine", you would be able to look up tangerine and give me the definition.What's common in these 2 functions? I ask <strong>for</strong> something by giving you a letter or aword (ie, a key), and you give me back something that relates to that key (ie, a value<strong>for</strong> that key). The dictionary is mapping keys to values. Can you think of anythingelse in real life that acts like a dictionary? I can think of a couple: an encyclopedia ora phone book.Since we use dictionaries in real life, it makes sense to have them in computerprogramming, too (like lists!). Going back to Facebook, Facebook might want to usea dictionary to map a person's name to their friends. Netflix might use a dictionary tomap a user to their queue of movies. The contact list on your cell phone might mapyour friends' names to their phone number.Let's see how this works in python. In python, the dictionary is represented as curlybrackets ({}). 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 numbersto 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 learnedabout earlier? That's cuz it's identical. Yea. One less thing to remember! Lists are justdictionaries with integers as keys.Step 2. Now that we have Bob in our address book, let's say you want to get hisphone 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 invariables, so we could even do something like this: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 phonenumbers 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 4).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, youcan 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 onlybeen 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 alist of tv shows to a channel? For example, we could map the channel PBS to a list ofshows on PBS. See if you can figure the code out on your own first. (Some shows onPBS are "Arthur", "Angelina Ballerina" and "Sid the <strong>Science</strong> Kid". If you need help,one possible answer is in Appendix A (Solution 5)!


Lesson 8. LoopsFor loopsRemember the other problem we wanted to solve earlier: what if we wanted to loopthrough every item in a list and per<strong>for</strong>m some operation on the value? For example,let's say we had a list of names, maybe all your friends on Facebook, and we wantedto print out all their names. You could say it like this: <strong>for</strong> each friend in my friend list,print the person's name. I'll write it one more way:friends = ['Stephanie', 'Amy', 'Candice', 'Maggie']<strong>for</strong> name in friends:print nameGuess what! That's python code! This is called a <strong>for</strong> loop. The <strong>for</strong> loop loops througheach item in the list and allows you to per<strong>for</strong>m some operation on that item. In thisexample, our operation is to print the item. Look at the structure of this code. Similarto our if statements, there's a code block that's indented. Although this example hasonly one line of code in the block, there can be more than one line. Each line has tobe indented the same amount. Also notice that there's another colon at the end, justlike the if statements!Here's a more complex example. Let's say we wanted to create a website that foundthe best deals on clothes by "scraping" other sites <strong>for</strong> pricing in<strong>for</strong>mation. Forexample, we might scrape macys.com and nordstrom.com <strong>for</strong> the price of a pair ofGuess jeans. We would first save the links in a list. We could then open a connectionto each link and get the contents of the page. We could have a certain pattern wemight want to match on the page, maybe something like $number.number, and saveany content that matches that pattern <strong>for</strong> later use. Here's what the code might looklike (don't worry if you don't understand it all, just notice that it uses a <strong>for</strong> loop!):urls = ["http://www.macys.com/product/3214", "http://www.nordstrom.com/product/425", "http://www.jcpenney.com/product/id=452"]<strong>for</strong> 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 <strong>Python</strong> Shell.Step 1. Enter the following code and hit Enter twice:<strong>for</strong> i in range(5):print iWhat happens when you run the code? This should be printed:01234Step 2. Why does the previous code print 0 to 4? To answer that question, try typingthis into the <strong>Python</strong> Shell:print range(5)What is printed? [0, 1, 2, 3, 4]. What does that look like? If you guessed a list, youwould be correct! The range method is creating a list of integers from 0 to 4. The liststarts at 0, then ends at the number be<strong>for</strong>e 5. If you tried range(10), can you guesswhat list would be created?Step 3. Let's try another example. Type this code into the <strong>Python</strong> Shell to see what itdoes:phone_numbers = { "Anna":"415-555-1234", "James":"650-555-1524","Mike":"408-555-1234" }<strong>for</strong> name in phone_numbers.keys():print phone_numbers[name]Remember that the keys() method retrieves a list of all the keys in the dictionary. Theloop then loops through all the keys and uses the key to print associated phonenumber.Step 4. Your turn! Write code to do the following: <strong>for</strong> each number in the range 0 to9, print the result of that number times itself. (See Appendix A, Solution 6 <strong>for</strong> onepossible solution)


While loopsThere's another type of loop available in python: while loops. The basic idea behind awhile loop is that the loop keeps running the code block while something is true andstops once it become false. For example, you might want to build a music player thatkeeps playing music while the user has not pressed the stop button. Once the userpresses the stop button, the program stops playing the music.Here's a simple example of a while loop:counter = 1while counter < 10:print countercounter = counter + 1What does this code do? It keeps printing the counter value until the counter is nolonger less than 10. While loops have a boolean expression, just like if statements. Inthis example, why does the counter value increase? Because you keep adding 1 everytime you loop (line 4). What would happen if you didn't add one to the counter or didsomething like this:counter = 1while counter < 10:print countercounter = 1This will run <strong>for</strong>ever! We call this an infinite loop. Sometimes you might want to usean infinite loop, but most often you don't. :) An infinite loop could also be writtenlike this:while True: print 'hi'Time to practice.Step 0. Open the <strong>Python</strong> Shell if you haven't done so already.Step 1. Try this code <strong>for</strong> yourself:counter = 1while counter < 10:


print countercounter = counter + 1Does 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 AppendixA, Solution 7 <strong>for</strong> one possible solution)Remember you did something like this with a <strong>for</strong> loop? Often what can beaccomplished with a <strong>for</strong> 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 thecode you should have so far in your giftcard.py file (if it's not the same, take amoment to change it to match):gift_card_value = 20cost = 12sales_tax_rate = .095tax = cost * sales_tax_ratetotal_cost = tax + costprint total_costleft_over = gift_card_value - total_costif left_over < 0:print "Over budget"else:print "OK"print left_overLet'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 canuse 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 tosee 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 wantcost to represent the entire cost of all the items, adding each item's cost to this valueas the user enters it. Once the user enters 'q', the program would stop asking <strong>for</strong>input from the user and then continue with the rest of the calculations. Here are thesteps:get the gift card valueset the cost variable to zeroget 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 programTry to translate these steps to python code. (See Appendix A, Solution 8 <strong>for</strong> onepossible solution)Appendix A. SolutionsSolution 1.print name+" who?"Solution 2.Just rightSolution 3.A little bit coldSolution 4.phone_book['name'] = '415-555-1234'


orphone_book['Bob'] = '415-555-1234'Solution 5.gift_card_value = 20cost = 12sales_tax_rate = .095tax = cost * sales_tax_ratetotal_cost = tax + costprint total_costleft_over = gift_card_value - total_costif left_over < 0:print "Over budget"else:print "OK"print left_overSolution 6.<strong>for</strong> i in range(10):print i*iSolution 7.counter = 0while counter < 5:print countercounter = counter + 1Solution 8.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 = 0while 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_ratetotal_cost = tax + costprint total_costleft_over = gift_card_value - total_costif left_over < 0:print "Over budget"else:print "OK"print left_over

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!