Latest revision |
Your text |
Line 73: |
Line 73: |
| >>> names | | >>> names |
| ['Eliza', 'Harriet', 'Henry', 'Joe', 'Pat', 'Wanda'] | | ['Eliza', 'Harriet', 'Henry', 'Joe', 'Pat', 'Wanda'] |
| >>> names.sort(reverse=True)
| |
| ['Wanda', 'Pat', 'Joe', 'Henry', 'Harriet', 'Eliza']
| |
|
| |
|
| ==== Getting the maximum and minimum values from a list ==== | | ==== Getting the maximum and minimum values from a list ==== |
Line 84: |
Line 82: |
| -1 | | -1 |
|
| |
|
| | ===Strings=== |
|
| |
|
| | ;Strings are a lot like lists |
| | >>> my_string = "Hello World" |
| | >>> my_string[0] |
| | 'H' |
| | >>> my_string[:5] |
| | 'Hello' |
| | >>> my_string[6:] |
| | 'World' |
| | >>> my_string = my_string[:6] + "Jessica" |
| | >>> my_string |
| | 'Hello Jessica' |
| | >>> 'H' in my_string |
| | True |
|
| |
|
| == New concepts for Week 3 exercises and challenges ==
| | ;String formatting |
| | |
| ===More string functions===
| |
| | |
| ==== Formatting strings ====
| |
| Formatting strings makes it much easier to combine alphanumeric characters and other types of object (like ints, floats, and bools) and do things with them—like print!
| |
| | |
| >>> x = 1 | | >>> x = 1 |
| >>> y = 1.234 | | >>> y = 1.234 |
Line 98: |
Line 104: |
| >>> w = "elevator" | | >>> w = "elevator" |
| >>> all_together_now = "You can put ints like %d, floating point numbers like %f, boolean values like %s, and other strings like %s into a string without changing them to strings first!" % (x,y,z,w) | | >>> all_together_now = "You can put ints like %d, floating point numbers like %f, boolean values like %s, and other strings like %s into a string without changing them to strings first!" % (x,y,z,w) |
| >>> print(all_together_now)
| |
|
| |
| ==== Dealing with whitespace ====
| |
| >>> text = " this is a text string with lots of extra spaces "
| |
| >>> text.strip()
| |
| "this is a text string with lots of extra spaces"
| |
| >>> text.split()
| |
| ['this', 'is', 'a', 'text', 'string', 'with', 'lots', 'of', 'extra', 'spaces']
| |
| >>> " ".join(text.split())
| |
| 'this is a text string with lots of extra spaces'
| |
|
| |
|
| |
| ==== Tuples ====
| |
| Tuples are similar to lists, but unlike lists, once they're created ("assigned") they can't be changed. Since most of our work involves reading and writing files and building and manipulating sets of data, we might not have too much cause to use tuples. But Python uses them a lot "behind the scenes", and they're useful for other types of programming, so we'll go over them briefly here.
| |
|
| |
| You can create a tuple just like a list...
| |
| >>> my_tuple = ("John", "Terry", "Terry", "Graham", "Eric")
| |
|
| |
| You can find items by index...
| |
| >>> my_tuple[1]
| |
| 'Terry'
| |
|
| |
| BUT you can't edit them...
| |
| >>> my_tuple[1] = "John"
| |
| ---------------------------------------------------------------------------
| |
| TypeError Traceback (most recent call last)
| |
| <ipython-input-63-2dfac7e646ea> in <module>()
| |
| ----> 1 my_tuple[1] = "Michael"
| |
|
| |
| TypeError: 'tuple' object does not support item assignment
| |
|
| |
|
| |
|
| | == New concepts for Week 3 exercises and challenges == |
| ====Generating a list of numbers easily with <code>range()</code>==== | | ====Generating a list of numbers easily with <code>range()</code>==== |
|
| |
|
Line 136: |
Line 112: |
| [0, 1, 2, 3, 4] | | [0, 1, 2, 3, 4] |
| >>> for i in range(5): | | >>> for i in range(5): |
| ... print("Hi" * i) | | ... print "Hi" * i |
| ... | | ... |
|
| |
|
Line 171: |
Line 147: |
| 9 | | 9 |
| 16 | | 16 |
|
| |
| You can also set the start, end, and increment value (called "step") for a range.
| |
| >>> for i in range(2,20,2):
| |
| ... print(i)
| |
| 2
| |
| 4
| |
| 6
| |
| 8
| |
| 10
| |
| 12
| |
| 14
| |
| 16
| |
| 18
| |
|
| |
| === Using break statements to halt execution ===
| |
| word_list = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
| |
| letter = "z"
| |
| seen_letter = False
| |
| for word in word_list:
| |
| if letter in word:
| |
| seen_letter = True
| |
| print("%s contains the letter %s" % (word, letter))
| |
| else:
| |
| print("no %s in %s" % (letter, word))
| |
|
| |
|
| === Get user input with <code>input()</code> === | | === Get user input with <code>input()</code> === |
Line 200: |
Line 152: |
| >>> for i in range(100): | | >>> for i in range(100): |
| ... my_input = input("Please type something> ") | | ... my_input = input("Please type something> ") |
| ... if my_input == "Quit": | | ... if input == "Quit": |
| ... print("Goodbye!") | | ... print("Goodbye!") |
| ... break | | ... break |
Line 213: |
Line 165: |
| Goodbye! | | Goodbye! |
| >>> | | >>> |
|
| |
| === Iterating an indeterminate number of times with <code>while</code> loops ===
| |
|
| |
| grocery_list = []
| |
| testAnswer = input('Press y if you want to enter more groceries: ')
| |
| while testAnswer == 'y':
| |
| food = input('Next item:')
| |
| grocery_list.append(food)
| |
| testAnswer = input('Press y if you want to enter more groceries: ')
| |
|
| |
| print('Your grocery list:')
| |
| for food in grocery_list:
| |
| print(food)
| |
|
| |
|
| ===Dictionaries=== | | ===Dictionaries=== |
Line 247: |
Line 186: |
| <type 'dict'> | | <type 'dict'> |
|
| |
|
| ====Adding and removing elements ==== | | ====Adding elements to a dictionary==== |
|
| |
|
| >>> your_dict["Dora"] = "vanilla" | | >>> your_dict["Dora"] = "vanilla" |
| >>> your_dict | | >>> your_dict |
| {'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'chocolate'} | | {'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'chocolate'} |
|
| |
| >>> del your_dict["Dora"]
| |
| >>> your_dict
| |
| {'Bob': 'strawberry', 'Cara': 'mint chip', 'Alice': 'chocolate'}
| |
|
| |
|
| ====Accessing elements of a dictionary==== | | ====Accessing elements of a dictionary==== |
Line 300: |
Line 235: |
|
| |
|
| ====Looping through a dictionary==== | | ====Looping through a dictionary==== |
| The builtin functions <code>.items(), .keys(),</code> and <code>.values()</code> provide you with a lot of flexibility when iterating through dictionaries.
| |
|
| |
|
| >>>for i in your_dict.items(): | | >>>for i in your_dict.items(): |
Line 339: |
Line 273: |
| chocolate is the value for Alice | | chocolate is the value for Alice |
|
| |
|
| ==== Sorting dictionaries with <code>operator</code> and <code>itemgetter</code> ====
| | * dict keys can be integers |
| | |
| We've already learned how you can use <code>.sorted()</code> to create a sorted version of a list. <code>.sorted()</code> accepts an optional <code>key</code> argument to tell it what to sort on. You can use <code>.sorted()</code> with <code>.items()</code> builtin dictionary function and the <code>itemgetter</code> function of the <code>operator</code> module to create sorted versions of dictionaries!
| |
| | |
| >>> import operator
| |
| >>> family = {'ozy':2, 'jonathan':34, 'portia':10, 'eva':6, 'dana':28}
| |
| >>> sorted(family.items(), key=operator.itemgetter(1), reverse=True)
| |
| [('jonathan', 34), ('dana', 28), ('portia', 10), ('eva', 6), ('ozy', 2)]
| |
| | |
| You can also use this approach to sort other complex data structures:
| |
| | |
| >>> family = [['ozy',2], ['portia',10], ['jonathan',34], ['dana', 28], ['eva', 6]]
| |
| >>> sorted(family, key=operator.itemgetter(1))
| |
| [['ozy', 2], ['eva', 6], ['portia', 10], ['dana', 28], ['jonathan', 34]]
| |
| >>> sorted(family, key=operator.itemgetter(0), reverse=True)
| |
| [['portia', 10], ['ozy', 2], ['jonathan', 34], ['eva', 6], ['dana', 28]]
| |
|
| |
|
| == Exercise == | | == Exercise == |
| <big>'''[http://jtmorgan.net/ds4ux/week3/notifications.zip Click here to download the scripts for this week's in-class exercise]'''</big> | | <big>'''[http://jtmorgan.net/ds4ux/week3/notifications.zip Click here to download the scripts for this week's in-class exercise]'''</big> |