Python for Beginners Python for Beginners...1

Similar documents
MITOCW watch?v=se4p7ivcune

MITOCW watch?v=0jljzrnhwoi

MITOCW watch?v=flgjisf3l78

Skill 1: Multiplying Polynomials

MITOCW watch?v=rvrkt-jxvko

BEGINNER PHP Table of Contents

The following content is provided under a Creative Commons license. Your support

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

MITOCW ocw f99-lec07_300k

The following content is provided under a Creative Commons license. Your support

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Post Experiment Interview Questions

MITOCW watch?v=9h6muyzjms0

Lesson 4: Who Goes There?

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Chapter 4 Lab. Loops and Files. Objectives. Introduction

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1

Starting. Read: Chapter 1, Appendix B from textbook.

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

the rules The Goal Get all three of your monkeys around the board and into the Banana Grove before anyone else can!

Python for Non-programmers

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

MITOCW watch?v=w_-sx4vr53m

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

The Big Python Guide

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

MITOCW watch?v=4dj1oguwtem

CS 190C: Introduction to Computational Thinking

Part III Appendices 165

Unit E Step-by-Step: Programming with Python

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

MITOCW ocw f99-lec12_300k

Expressions and Variables

If Statements, For Loops, Functions

C++ Reference NYU Digital Electronics Lab Fall 2016

CS Summer 2013

Decisions, Decisions. Testing, testing C H A P T E R 7

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Types, lists & functions

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Chapter 1 Operations With Numbers

Intro. Scheme Basics. scm> 5 5. scm>

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

C# Programming Tutorial Lesson 1: Introduction to Programming

Regular Expressions Explained

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Math Day 2 Programming: How to make computers do math for you

Lists, loops and decisions

Problem Solving for Intro to Computer Science

Full file at

MITOCW watch?v=yarwp7tntl4

printf( Please enter another number: ); scanf( %d, &num2);

(Python) Chapter 3: Repetition

How Do Robots Find Their Way?

Maxime Defauw. Learning Swift

Variables and Constants

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5

Out for Shopping-Understanding Linear Data Structures English

MITOCW watch?v=ytpjdnlu9ug

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

The following content is provided under a Creative Commons license. Your support

MIT AITI Python Software Development

Program Planning, Data Comparisons, Strings

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Text Input and Conditionals

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

GENERAL MATH FOR PASSING

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Condition Controlled Loops. Introduction to Programming - Python

Module 6. Campaign Layering

Memory Addressing, Binary, and Hexadecimal Review

Python Intro GIS Week 1. Jake K. Carr

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Repetition Structures

The Stack, Free Store, and Global Namespace

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

PROFESSOR: Well, yesterday we learned a bit about symbolic manipulation, and we wrote a rather stylized

Introduction to programming with Python

Python: common syntax

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Programming Fundamentals and Python

Welcome to Python 3. Some history

QUICK EXCEL TUTORIAL. The Very Basics

Arduino IDE Friday, 26 October 2018

MITOCW watch?v=kz7jjltq9r4

Python 1: Intro! Max Dougherty Andrew Schmitt

Instructor: Craig Duckett. Lecture 03: Tuesday, April 3, 2018 SQL Sorting, Aggregates and Joining Tables

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Unit 9 Tech savvy? Tech support. 1 I have no idea why... Lesson A. A Unscramble the questions. Do you know which battery I should buy?

Intro. Classes & Inheritance

Making ecards Can Be Fun!

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Transcription:

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

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. Python, is well-known for being an easy language to learn. Lesson 1. My First Python Program Let's start with a simple python program. Step 0. Open Python Shell by going Start (Windows logo at the bottom left) ->All Programs->Python 2.7->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 "Alice in Wonderland" Step 2. What happens? Alice in Wonderland 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 "Oh dear! Oh dear! I shall be too late!" print "DRINK ME" print "EAT ME"

Lesson 2. Input from user Now your program can print all the things the white rabbit says, the bottle says, and the cookie says. How about what YOU want to tell the program? Step 0. If you haven't done so already, open a Python 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 showed Enter 1 if you want to drink me, 2 if you don't: Step 3. Answer with 1 or 2. What happens? Lesson 3. Variables Now we can get the input from user, but for more fun, we want "react" to what user has said. For example, if the user said 1, then we want to shrink Alice! To do so, your program needs to remember what the user said. A computer program remembers by storing what user has said in a "variable". 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 answer or rabbit or firstname. Then we 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:

firstname = "Alice" print firstname This might not seem very interesting, but it is! The variable, firstname, is being assigned "Alice". The quotation marks around Alice means that this is a String - a text. The print command is printing the value, what's inside of the variable firstname. What can we do with this? Step 2. Let's try adding the last name to the first name. Type the following into the command line: firstname + " Lewis" What happens? 'Alice Lewis' should be printed! The single quotation marks mean that Python understands that Alice Lewis is a text. The python interpreter is using the value of "Alice" for the variable firstname and is adding " Lewis" to "Alice", which turns out to be a new text "Alice Lewis". Step 3. What if we created another variable, let's say lastname and assigned that a value. Could we then add firstname and lastname? Try these commands: lastname = "Lewis" firstname + " " + lastname You should see 'Alice Lewis' 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 firstname: firstname = "Carol" print firstname firstname 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 help you realize how powerful this can be. It will be called "Knock Knock Joke". Your program 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 say the 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 to see if it has the correct name. print name Great, now we have the name you typed. Can you figure out how to print "who?" after the name? (Solution 1 in Appendix A) 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 knockknock.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 ================================ >>> Knock Knock Who's there? Lesson 4. If Statements "OK, great," you might say, "I can create variables. I can do knock knock jokes. But this 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 message based on the number?" For example, you might want to print a simple message such as "Alice shrank!" or "A white rabbit just passed!" based on the number. You could think 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 in another 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 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. 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: print "Hot" else: #<- colon here print "Cold" #<- colon here

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. 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 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 == "Alice" Meaning: name is equal to "Alice" 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: 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 2, Appendix A) What if the temperature was 66? (Solution 3, Appendix A) Let's try an example. Step 1. Open a Python 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 Python Shell. Lesson 5. Simple Loops Imagine that you have to do the same thing over and over again. It would be tiring and boring, right? Computers are perfect for doing the repetition for you. Let's start with printing the same thing multiple times. Step 1. Given the following print statement, what will happen? print "*"*5 Step 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.

>>> for 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 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". 1 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: 1. http://en.wiktionary.org/wiki/data_type

"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. 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 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" "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. 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? OK, moving on to data structures...

Lesson 7. 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 PBS. 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 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("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 tvshows Yup, Curiosity Quest 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 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 = ["Arthur", "Angelina Ballerina", "WordGirl"] 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] = "Martha Speaks"

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] = "High School Musical" 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: 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. 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: 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 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, 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 PBS to a list of shows on PBS. See if you can figure the code out on your own first. (Some shows on PBS are "Arthur", "Angelina Ballerina" and "Sid the Science Kid". If you need help, one possible answer is in Appendix A (Solution 5)!

Lesson 8. 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 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: 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. 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 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): 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: 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 1. print name+" who?" Solution 2. Just right Solution 3. A little bit cold Solution 4. phone_book['name'] = '415-555-1234'

or phone_book['bob'] = '415-555-1234' 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. 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