class: center, middle
# Coding Club ## week 2 --- # Recap 1. Variables 2. Functions --- # Variables Last time we got to talk about two different variables types ## integers example: ```python radius = 1 pi = 3.1415926535 print pi * r ** 2 ``` output: 9.86960437853 --- # Variables Last time we got to talk about two different variables types ## integers example: ```python radius = 1 pi = 3.1415926535 print pi * r ** 2 ``` ``` 9.86960437853 ``` ## strings example: ```python greeting = "Hello World!" print greeting ``` ``` Hello World! ``` --- # Functions Last time we also talked about some "built-in" functions --- # Functions Last time we also talked about some "built-in" functions ## raw\_input() example: ```python print "What is your name? " name = raw_input() print "Hello ", name ``` ``` What is your name? > Mark Hello Mark ``` --- # Functions Last time we also talked about some "built-in" functions ## raw\_input() example: ```python print "What is your name? " name = raw_input() print "Hello ", name ``` ``` What is your name? > Mark Hello Mark ``` ## math.sqrt(number) example: ```python import math print "Say something irrational" print math.sqrt(2) ``` ``` Say something irrational 1.41421356237 ``` --- # User Defined Functions Finally we talked about defining your own function --- # User Defined Functions Finally we talked about defining your own function ```python import math def pythag(a, b): return math.sqrt(a ** 2 + b ** 2) ``` --- # User Defined Functions Finally we talked about defining your own function ```python import math def pythag(a, b): return math.sqrt(a ** 2 + b ** 2) ``` Here we define a function called `pythag` with "arguments" `a` and `b` --- # User Defined Functions Finally we talked about defining your own function ```python import math def pythag(a, b): return math.sqrt(a ** 2 + b ** 2) ``` Here we define a function called `pythag` with "arguments" `a` and `b` Remember that the `return` keyword specifies the value that the function evaluates to --- # This Time - String Manipulation - Lists - Putting Them Together --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
went to the store" --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
Mark
went to the store" --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
Mark
went to the store" This operation is known as "string interpolation" or just "interpolation" --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
Mark
went to the store" This operation is known as "string interpolation" or just "interpolation" ## How it's done In python this is accomplished through the `.format` function. --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
Mark
went to the store" This operation is known as "string interpolation" or just "interpolation" ## How it's done In python this is accomplished through the `.format` function. ```python print "One day {} went to the store".format("Mark") ``` ``` One day Mark went to the store ``` --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
Mark
went to the store" This operation is known as "string interpolation" or just "interpolation" ## How it's done In python this is accomplished through the `.format` function. ```python print "One day {} went to the store".format("Mark") ``` ``` One day Mark went to the store ``` you can also use multiple arguments ```python print "{} is {}'s favorite day to {}".format("Saturday", "John", "sleep") ``` ``` Saturday is John's favorite day to sleep ``` --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
Mark
went to the store" This operation is known as "string interpolation" or just "interpolation" ## How it's done In python this is accomplished through the `.format` function. ```python print "One day {} went to the store".format("Mark") ``` ``` One day Mark went to the store ``` you can also use multiple arguments ```python print "{} is {}'s favorite day to {}".format("Saturday", "John", "sleep") ``` ``` Saturday is John's favorite day to sleep ``` **Note:** if you just have `{}` the formatter will automatically advance to the "next" argument --- # String Manipulation (Interpolation) ## Idea Suppose that during your python program you wanted to insert a string in the middle of another string "One day
Mark
went to the store" This operation is known as "string interpolation" or just "interpolation" ## How it's done In python this is accomplished through the `.format` function. ```python print "One day {} went to the store".format("Mark") ``` ``` One day Mark went to the store ``` you can also use multiple arguments ```python print "{} is {}'s favorite day to {}".format("Saturday", "John", "sleep") ``` ``` Saturday is John's favorite day to sleep ``` **Note:** if you just have `{}` the formatter will automatically advance to the "next" argument You can also reuse arguments ```python print "The r{0} in sp{0} falls {1} in the pl{0}s".format("ain", "mostly") ``` ``` The rain in spain falls mostly in the plains ``` --- # String Manipulation (aside) ## Methods What's with the weird `"string".format` notation? Whenver you see `variable.something` python in invoking the "method" called "something" on "variable" A method is just a function that's bound to an object. We'll talk about objects more later but for now I'll just say that a string is a type of object --- # String Manipulation (Concatenation) ## Idea Suppose that during your python program you wanted to combine two strings --- # String Manipulation (Concatenation) ## Idea Suppose that during your python program you wanted to combine two strings You could use the method we _just_ talked about but there's a simpler way --- # String Manipulation (Concatenation) ## Idea Suppose that during your python program you wanted to combine two strings You could use the method we _just_ talked about but there's a simpler way ## How's it done ```python print "That was " + "easy" ``` ``` That was easy ``` This is known as "string concatenation" or just "concatention" in programmer parlance --- # String Manipulation (Length) ## Idea What about finding the length of a string? ## How's it done ```python print len("How many letters do I have") ``` ``` 26 ``` --- # String Manipulation (Length) ## Idea What about finding the length of a string? ## How's it done ```python print len("How many letters do I have") ``` ``` 26 ``` Why is `len` not a method? --- # String Manipulation (Length) ## Idea What about finding the length of a string? ## How's it done ```python print len("How many letters do I have") ``` ``` 26 ``` Why is `len` not a method? In short because it's used for other things (that aren't strings). We'll get to that later --- # String Manipulation (Others) There are a **lot** of other cool string methods ```python str.capitalize() str.center(width[, fillchar]) str.count(sub[, start[, end]]) str.decode([encoding[, errors]]) str.encode([encoding[, errors]]) str.endswith(suffix[, start[, end]]) str.expandtabs([tabsize])ΒΆ str.find(sub[, start[, end]]) str.index(sub[, start[, end]]) str.isalnum() str.isalpha() str.isdigit() str.islower() str.isspace() str.istitle() (seriously?) str.isupper() str.replace(old, new[, count]) ... ``` but I'm not going to go into detail on all of them --- # Lists (Syntax) ## Idea A list is just an ordered collection of things --- # Lists (Syntax) ## Idea A list is just an ordered collection of things. ## How's it done ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] print groceries ``` ``` ['Eggs', 'Oatmeal', 'An entire cow', 'A meat cleaver'] ``` --- # Lists (Access) ## Idea In order to access a specific "element" of a list you use the `[index]` notation --- # Lists (Access) ## Idea In order to access a specific "element" of a list you use the `[index]` notation ## How's it done ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] print groceries[0] ``` ``` Eggs ``` Here we would say that "Eggs" is element at index `0` --- # Lists (Access) ## Idea In order to access a specific "element" of a list you use the `[index]` notation ## How's it done ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] print groceries[0] ``` ``` Eggs ``` Here we would say that "Eggs" is element at index `0` ### Why do the indices start at `0`? --- # Lists (Access) ## Idea In order to access a specific "element" of a list you use the `[index]` notation ## How's it done ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] print groceries[0] ``` ``` Eggs ``` Here we would say that "Eggs" is element at index `0` ### Why do the indicies start at `0`? C/C++ do it this way Relationship to memory alignment Dijkstra and half open intervals etc.
--- # Lists (Access) ## Idea In order to access a specific "element" of a list you use the `[index]` notation ## How's it done (cont.) ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] print "Don't forget to buy {} and {}".format(groceries[0], groceries[2]) ``` ``` Don't forget to buy Eggs and An entire cow ``` --- # List Access (Slicing) ## Idea What if you only need a certain subsection of list? --- # List Access (Slicing) ## Idea What if you only need a certain subsection of list? ## How's it done The notation is basically `[start:end]` ```python words = ["My", "name", "is", "Judge"] print words[0:2] ``` ``` ['My', 'name'] ``` --- # List Access (Slicing) ## Idea What if you only need a certain subsection of list? ## How's it done The notation is basically `[start:end]` ```python words = ["My", "name", "is", "Judge"] print words[0:2] ``` ``` ['My', 'name'] ``` `start` or `end` can be omitted and the selection will continue to the beginning or the end of the array (respectively) ```python words = ["My", "name", "is", "Judge"] print words[1:] ``` ``` ['name', 'is', 'Judge'] ``` --- # List Access (Slicing) ## Idea What if you only need a certain subsection of list? ## How's it done The notation is basically `[start:end]` ```python words = ["My", "name", "is", "Judge"] print words[0:2] ``` ``` ['My', 'name'] ``` `start` or `end` can be omitted and the selection will continue to the beginning or the end of the array (respectively) ```python words = ["My", "name", "is", "Judge"] print words[1:] ``` ``` ['name', 'is', 'Judge'] ``` ```python words = ["My", "name", "is", "Judge"] print words[:1] ``` ``` ['My'] ``` --- # List Access (Slicing) ## Idea What if you only need a certain subsection of list? ## How's it done The notation is basically `[start:end]` ```python words = ["My", "name", "is", "Judge"] print words[0:2] ``` ``` ['My', 'name'] ``` `start` or `end` can be omitted and the selection will continue to the beginning or the end of the array (respectively) ```python words = ["My", "name", "is", "Judge"] print words[1:] ``` ``` ['name', 'is', 'Judge'] ``` ```python words = ["My", "name", "is", "Judge"] print words[:1] ``` ``` ['My'] ``` ```python words = ["My", "name", "is", "Judge"] print words[:] ``` ``` ['My', 'name', 'is', 'Judge'] ``` --- # List Manipulation (Insertion) ## Idea What if you need to add something to a list --- # List Manipulation (Insertion) ## Idea What if you need to add something to a list ## How's it done You can add an item to the end of a list using `append` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.append("seasoning") print groceries ``` ``` ['Eggs', 'Oatmeal', 'An entire cow', 'A meat cleaver', 'seasoning'] ``` --- # List Manipulation (Insertion) ## Idea What if you need to add something to a list ## How's it done You can add an item to the end of a list using `append` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.append("seasoning") print groceries ``` ``` ['Eggs', 'Oatmeal', 'An entire cow', 'A meat cleaver', 'seasoning'] ``` You can add an item to an arbitrary position by using `insert` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.insert(2, "A bigger car") print groceries ``` ``` ['Eggs', 'Oatmeal', 'A bigger car', 'An entire cow', 'A meat cleaver'] ``` --- # List Manipulation (Removal) ## Idea What if you need to remove something from a list --- # List Manipulation (Removal) ## Idea What if you need to remove something from a list ## How's it done To remove the element at the back of a list you can use `pop` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.pop() print groceries ``` ``` ['Eggs', 'Oatmeal', 'An entire cow'] ``` --- # List Manipulation (Removal) ## Idea What if you need to remove something from a list ## How's it done To remove the element at the back of a list you can use `pop` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.pop() print groceries ``` ``` ['Eggs', 'Oatmeal', 'An entire cow'] ``` `pop` actually returns the element that was just removed which you can save for later like so ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] last_item = groceries.pop() print "On second thought let's not get {}".format(last_item) ``` ``` On second thought let's not get A meat cleaver ``` --- # List Manipulation (Removal) ## Idea What if you need to remove something from a list ## How's it done To remove the element at the back of a list you can use `pop` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.pop() print groceries ``` ``` ['Eggs', 'Oatmeal', 'An entire cow'] ``` `pop` actually returns the element that was just removed which you can save for later like so ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] last_item = groceries.pop() print "On second thought let's not get {}".format(last_item) ``` ``` On second thought let's not get A meat cleaver ``` If you need to remove the first element with a specific value you can use `remove` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.remove("An entire cow") print groceries ``` ``` ['Eggs', 'Oatmeal', 'A meat cleaver'] ``` --- # List Manipulation (Removal) ## Idea What if you need to remove something from a list ## How's it done To remove the element at the back of a list you can use `pop` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.pop() print groceries ``` ``` ['Eggs', 'Oatmeal', 'An entire cow'] ``` `pop` actually returns the element that was just removed which you can save for later like so ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] last_item = groceries.pop() print "On second thought let's not get {}".format(last_item) ``` ``` On second thought let's not get A meat cleaver ``` If you need to remove the first element with a specific value you can use `remove` ```python groceries = ["Eggs", "Oatmeal", "An entire cow", "A meat cleaver"] groceries.remove("An entire cow") print groceries ``` ``` ['Eggs', 'Oatmeal', 'A meat cleaver'] ``` **Note:** `remove` does not return the value of the element removed --- # List Operations (Index) ## Idea What if you need to find which "index" corrosponds to a given "element" --- # List Operations (Index) ## Idea What if you need to find which "index" corrosponds to a given "element" ## How's it done ```python characters = ["Fred", "Steve", "Sally", "Bob", "Willma", "Tracey", "Waldo", "Dino"] where_is_waldo = characters.index("Waldo") print "Waldo is at index {}".format(where_is_waldo) ``` ``` Waldo is at index 6 ``` --- # List Operations (Index) ## Idea What if you need to find which "index" corrosponds to a given "element" ## How's it done ```python characters = ["Fred", "Steve", "Sally", "Bob", "Willma", "Tracey", "Waldo", "Dino"] where_is_waldo = characters.index("Waldo") print "Waldo is at index {}".format(where_is_waldo) ``` ``` Waldo is at index 6 ``` You have to be careful to not look for things that aren't there though ```python characters = ["Fred", "Steve", "Sally", "Bob", "Willma", "Tracey", "Waldo", "Dino"] characters.index("that guy") ``` ``` Traceback (most recent call last): File "
", line 2, in
ValueError: 'that guy' is not in list ``` --- # List Operations (Length) Remember how I said that `len` could be used on other non-string things? --- # List Operations (Length) Remember how I said that `len` could be used on other non-string things? ```python print len(['a', 'short', 'list', 'of', 'words']) ``` ``` 5 ``` --- # List Operations (Other) There are only a few other list methods that we won't touch on (but hopefully they're pretty obvious) ``` list.sort() (sorts a list alphabetically) list.reverse() (reverses a list) list.count(x) (counts the number of times x appears in the list) ``` --- # Lists Meet Strings There are a couple of cool list-string interactions. --- # Lists Meet Strings There are a couple of cool list-string interactions. ## Join ### Idea Let's say you wanted to join a list of words by some seperators like a `...` into one string --- # Lists Meet Strings There are a couple of cool list-string interactions. ## Join ### Idea Let's say you wanted to join a list of words by some seperators like a `...` into one string ### How's it done ```python print "... ".join(["One", "Two", "Three"]) ``` ``` One... Two... Three ``` --- # Lists Meet Strings There are a couple of cool list-string interactions. ## Join ### Idea Let's say you wanted to join a list of words by some seperators like a `...` into one string ### How's it done ```python print "... ".join(["One", "Two", "Three"]) ``` ``` One... Two... Three ``` Here we pass a list (note the `[]`) as an "argument" to `join` --- # Lists Meet Strings There are a couple of cool list-string interactions. ## Join ### Idea Let's say you wanted to join a list of words by some seperators like a `...` into one string ### How's it done ```python print "... ".join(["One", "Two", "Three"]) ``` ``` One... Two... Three ``` Here we pass a list (note the `[]`) as an "argument" to `join` ## Going the other way (Split) ### How's it done ```python print "One... Two... Three".split("... ") ``` ``` ['One', 'Two', 'Three'] ``` --- # Lists Meet Strings There are a couple of cool list-string interactions. ## ...wait You may have already noticed how that this works --- # Lists Meet Strings There are a couple of cool list-string interactions. ## ...wait You may have already noticed how that this works ```python name = "Admiral Turtle" print name[8:] ``` ``` Turtle ``` --- # Lists Meet Strings There are a couple of cool list-string interactions. ## ...wait You may have already noticed how that this works ```python name = "Admiral Turtle" print name[8:] ``` ``` Turtle ``` you can actually access elements of a string just like you can with a list! --- # Practice ## We're going to make a MadLib generator! Dear
Relative
,
I am having a(n)
Adjective
time at camp. The counselour is
Adjective
and the food is
Adjective
. I met
Name of person in room
and we became
Adjective
friends. Unfortunately, is
Adjective
and I
Verb ending in "ED"
my
Body Part
so we couldn`t go
Verb ending in "ING"
like everybody else. I need more
Noun (Plural)
and a
Noun
sharpener, so please
Adverb
Verb
more when you
Verb
back.
Your
Relative
,
Person in room
Make a function which takes a MadLib `string` and a `list` of words to substitute into the MadLib then prints out the result ## Advanced Version Prompt a user for each of the blanks and build the list. Print out the result at the end --- # Practice ## We're going to make a MadLib generator! Dear
Relative
,
I am having a(n)
Adjective
time at camp. The counselour is
Adjective
and the food is
Adjective
. I met
Name of person in room
and we became
Adjective
friends. Unfortunately, is
Adjective
and I
Verb ending in "ED"
my
Body Part
so we couldn`t go
Verb ending in "ING"
like everybody else. I need more
Noun (Plural)
and a
Noun
sharpener, so please
Adverb
Verb
more when you
Verb
back.
Your
Relative
,
Person in room
Make a function which takes a MadLib `string` and a `list` of words to substitute into the MadLib then prints out the result ## Advanced Version Prompt a user for each of the blanks and build the list. Print out the result at the end ## Also this