Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists (also called Arrays) A list is an example of a collection: a data type that is capable of storing other data types. foods = ["spam", "eggs", "sausage",

Similar presentations


Presentation on theme: "Lists (also called Arrays) A list is an example of a collection: a data type that is capable of storing other data types. foods = ["spam", "eggs", "sausage","— Presentation transcript:

1 Lists (also called Arrays) A list is an example of a collection: a data type that is capable of storing other data types. foods = ["spam", "eggs", "sausage", "baked beans"] drinks = ["milk", "coffee"] oddDigits = [1, 3, 5, 7, 9] anEmptyList = [] Accessing elements of a list: >>> foods[2] 'sausage' >>> foods[0] 'spam' >>> foods[-1] 'baked beans' Adding to a list: >>> juiceName = "OJ" >>> drinks.append(juiceName) >>> drinks [ 'milk', 'coffee', 'OJ' ] Deleting from a list: >>> drinks.remove("coffee") # removes the first instance only >>> drinks [ 'milk', 'OJ' ]

2 Things You Can Do With Lists >> foods = ["spam", "eggs", "sausage", "baked beans"] >> waysToSayYes = ["yes", "Yes", "yep", "you bet", "oh yeah"]: Picking a random item from a list: >>> import random >>> print random.choice(foods) baked beans >>> print random.choice(foods) spam How many items in a list? >>> print len(foods) 4 >>> print len(anEmptyList) 0 Testing if an item is in a list: using the in keyword : while True: userResp = raw_input("Want to play again?") if userResp in waysToSayYes: play_game() else: break

3 More List Stuff... >>> my_list = [3, 9, 7, 5, 22, 6] Sorting a list: >>> my_list.sort() >>> print my_list [3, 5, 6, 7, 9, 22] Slicing a list: #these responses are for the sorted version of my_list. >>> my_list[3:] [7, 9, 22] >>> my_list[:3] [3, 5, 6] >>> my_list[2:4] [6, 7] # what values would you get for the unsorted list at the top? Concatenating two lists: >>> my_list = my_list + [16, 25, 36, 49] # you can do + but not - >>> print my_list [3, 9, 7, 5, 22, 6, 16, 25, 36, 49] Test yourself: what will be outputted by the following? print my_list[:3] + my_list[3:]

4 Lists and Strings... Splitting a string into a list of words >>> phrase = "When in the Course of human events... " >>> print phrase.split() ['When', 'in', 'the', 'Course', 'of', 'human', 'events.', '.', '.'] Counting instances of a particular item in a list >>> myScores = [ 18, 22, 17, 18, 21, 22, 22] >>> print myScores.count(22) 3 Strings can also be treated a lot like lists: >>> my_string = "Four score and seven years ago, etc." >>> print my_string[0] F >>> print my_string[-9:] ago, etc. >>> if letter in "aeiouAEIUO": print "Its a vowel!" >>> if word in my_string: print "yes, my_string contains the word", word

5 for x in [5,4,3,2,1]: print x print blast off! for loops in Python for loops work with lists. A for loop is used when you want to repeat some operation on every element in a list. Here is a for loop in Python: What do you think will be printed? It can also be done like this: countdown = [5,4,3,2,1] for x in countdown : print x print blast off! The values can be in any order. This also works fine: for x in [1,3,4,5,2,77,22]: print x Do you think the following is okay?: for x in [apples, bananas, cherries]: print I like, x

6 How exactly does a for loop work? the format of a for loop is: for someVariable in someList: do something... the first time through the loop, someVariable gets the value of the first element in someList the second time through the loop, someVariable gets the value of the second element and so forth... This is called iterating through the list Questions: What happens after it processes the last element in the list? What happens if the list is empty? Can you use break in a for loop?

7 range() range() returns a list of integers. With one parameter: it generates a list from 0 to one less than the number you give: >>> print range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] With two parameters: it generates a list from the first number to one less than the second number: >>> print range(10,20) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] With three parameters: it generates a list from the first number to one less than the second number, but stepping by the third parameter. Use this to count by twos: >>> print range(10,20,2) [10, 12, 14, 16, 18] or to count backwards: >>> print range(20,10,-1) [20, 19, 18, 17, 16, 15, 14, 13, 12, 11] or to count backwards by twos: >>> print range(20,10,-2) [20, 18, 16, 14, 12]

8 Using for with range It's extremely common in Python to combine for and range to create a loop that will run a specified number of times. Remember this?: for count in range(3): turn_left() Above, we aren't using the value of the variable called count – we're just using the fact that the list that range(3) creates has 3 elements. But sometimes the value of the loop counter variable is very useful... Remember this code from the IDLE worksheet? for radius in range(10, 150, 10): circle(150, 150, radius) If the graphics API circle(x,y,r) draws a circle of radius r at the point x,y, why does the code above draw the picture at the right? (Bonus question: can you tell from the code above how many rings there are? No fair counting from the picture... )

9 for/range and while equivalence You can generally rewrite a for/range using while, and vice versa for val in range(10): print val val = 0 while val < 10: print val val += 1 for val in range(2,10,2): print val val = 2 while val < 10: print val val += 2 for val in range(10,5,-2): print val val = 10 while val > 5: print val val -= 2 for loop: while loop:

10 What can you put in a loop? You can put any valid Python code in a loop, including: –conditional jumps –calls to subroutines –even other loops! yes, loops can be nested What does the following code print? for day in ["Mon", "Tue", "Wed", "Thu", "Fri"]: for myclass in ["PCT","A&P","Span","Math"]: print "On", day, "I go to", myclass print "then I go home" print "I do homework and sleep on weekends"

11 Loops can be nested The following will print out the multiplication table: for i in range(1,10): for j in range(1,10): print i, "times", j, "=", i*j Can you figure out what the following will do? for i in range(1,10): for j in range(i,10): print i, "times", j, "=", i*j

12 Livewires Graphics APIs Livewires is a set of Python routines that simplifies some computer graphics operations. To use it, your code must start with: from livewires import * To open up a graphics window that you can draw on, you must call begin_graphics() If you call it as above, you will get a white window 640 pixels wide x 480 high You can also call it with arguments to specify the height, width, background, and title. This is done with keyword arguments or keyword parameters. For example, the following creates a tall, skinny, red window: begin_graphics(height=500,width=100, background=Colour.red) You do not need to specify all keyword arguments, just the ones for which you dont want the default values To close the window, call: end_graphics()

13 box(x1, y1, x2, y2) – draw a box given two opposite corners. circle(x, y, r) – draw a circle with center at (x, y), radius r. box() and circle() also have two keyword parameters of interest: filled and colour. For filled, 1 means fill in the box or circle, 0 (the default) means dont. Colour allows you to set the color of the circle. More about specifying colors on the next slide clear_screen() – empty the graphics window Examples : circle(100,75,20) will draw the outline of a circle of radius 20 at x=100, y=75 circle(300,320,75, filled=1, colour=Colour.blue) will draw a filled-in blue circle of radius 75 at x=300, y=320 box(20,20,50,50,colour=Colour.red) will draw the outline of a red box with corners at 20,20 and 50,50 More Livewires Graphics APIs

14 Livewires Colours Just like there is a current position or point, there is a current color, er, colour. You change it by calling: set_colour(Colour.foo) – where foo is either red, green, blue, black, white, dark_grey, grey, light_grey, dark_red, dark_green, dark_blue, yellow, or brown. So you call it like this: set_colour(Colour.dark_green) You can also make custom colors from RGB values, using make_colour() and set_colour() together, like this: newShade = make_colour(red, green, blue) set_colour(newShade) In the call to make_colour above, red, green, and blue are variables – their values must be floating-point numbers between 0.0 and 1.0. You can also use a custom color like this: circle(90,90,50, colour=make_colour(0.3, 0.3, 0.3)) will give you a nice grey circle.

15 from livewires import * begin_graphics(300,300) for radius in range(10,150,5): circle(radius, radius, radius) circle(300 - radius, radius, radius) circle(radius, radius, radius) circle(300 - radius, radius, radius) Using Circles and a for Loop to Make a Surprisingly Cool Design


Download ppt "Lists (also called Arrays) A list is an example of a collection: a data type that is capable of storing other data types. foods = ["spam", "eggs", "sausage","

Similar presentations


Ads by Google