Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Portland Python Workshop

Portland Python Workshop

Slides by Michelle Rowley

Presented at the second Portland Python Workshop for Women held on July 28th & 29th, 2012, at Idealist. Sponsored by Decipher.

Avatar for Hacking Medusa

Hacking Medusa

July 28, 2012
Tweet

Other Decks in Education

Transcript

  1. Welcome to the Portland Python Workshop! Step 1: Join the

    Wifi Network Wifi Network: networkname Password: password Step 2: Get Python Installed Step 3: Start the Python Interactive Shell Step 4: Play!
  2. Portland Women's Software Academy Expand this Workshop into full-fledged school

    Currently in PIE: Portland Incubator Experiment Please participate in our R&D! Co-founder: Scott Deckelmann
  3. What to Expect Lessons in Python Pairing with neighbors Group

    activities Lots of practice Checks for understanding Fun! :)
  4. What to Expect * Quick assessment * People Bingo! *

    What is Programming? * Start speaking Python!
  5. What is a Computer? "A machine that stores and manipulates

    information under the control of a changeable program." - John Zelle, Python Programming
  6. What is a Computer Program? "A detailed step-by-step set of

    instructions telling a computer exactly what to do." - John Zelle, Python Programming
  7. Instructions for People "Clean your room." - my Mom, circa

    1992 "Mail your tax return no later than April 15th." - The US Government "Répondez, s'il vous plaît." - Anyone who ever told you to RSVP
  8. Syntax "...the study of the principles and processes by which

    sentences are constructed in particular languages". - Noam Chomsky (from Wikipedia)
  9. The Python Interactive Shell a.k.a. Python Interactive Interpreter, Python shell

    Easy to use Instant feedback The prompt - prompts you to type stuff: >>>
  10. Talking to Python: Numbers Arithmetic operators: addition: + subtraction: -

    multiplication: * Try doing some math in the interpreter: >>> 1 + 1 >>> 12 - 3 >>> 6 * 5
  11. Talking to Python: Numbers Another arithmetic operator: division: / Try

    doing some division in the interpreter: >>> 8/4 >>> 20/5 >>> 10/3 Is the last result what you expected?
  12. Talking to Python: Numbers Integers: 9 -55 Floats (have decimals):

    17.318 10.0 Try typing an integer and a float
  13. Talking to Python: Numbers Rule: If you want Python to

    respond to you in floats, you must talk to it in floats. >>> 11/3 >>> 3 >>> 11.0/3.0 >>> 3.6666666666666665
  14. Going Back in Time Up arrow brings commands back! Oops,

    no float: >>> 11/3 Edit instead of retyping: >>> 11.0/3.0 Try re-running a command
  15. Talking to Python: Strings >>> "apple" >>> "garlic breath" >>>

    "Thanks for coming!" Try typing one without quotes: >>> apple What's the result?
  16. Interlude: Errors Errors are no problem... they are essential! Python

    is trying to help. :) Let's make some errors: >>> apple >>> "baloney >>> Fun!"
  17. Talking to Python: Strings Rule: If it's a string, it

    must be in quotes "apple" "garlic breath" "Thanks for coming!"
  18. Talking to Python: Strings addition is concatenation: + Try concatenating

    (adding together strings): >>> "Hi" + "there!" 'Hithere'
  19. Talking to Python Quiz: Which ones will Python understand? What

    will the results be? 1. >>> 5 + 10 2. >>> "Three" + "Seven" + "Nine" 3. >>> "Happy" * 5 4. >>> "This is fun
  20. Talking to Python >>> 5 + 10 15 >>> "Three"

    + "Seven" + "Nine" 'ThreeSevenNine'
  21. Talking to Python >>> "friend" * 5 'friendfriendfriendfriendfriend' >>> "friend"

    + 5 Error Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
  22. Talking to Python: Errors Teach Us Traceback (most recent call

    last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects * Strings: 'str' * Integers: 'int' * Both are objects * Python cannot concatenate the two
  23. Talking to Python: Errors Teach Us Traceback (most recent call

    last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'float' objects Try to get THIS error on your own!
  24. Working Around Errors We want to display: How many eggs?

    12 >>>"How many eggs? " + 12 Error Concatenation won't work.
  25. Working Around Errors print command is for display: >>> print

    "How many eggs?", 12 How many eggs? 12 No concatenation, no problem!
  26. The print statement Note the differences in syntax: >>>"How many

    eggs? " + 12 Error >>>print "How many eggs?", 12 How many eggs? 12
  27. The print statement is handy You get spaces between items:

    >>>"This" + "isn't" + "great." Thisisn'tgreat. >>>print "This", "is", "awesome!" This is awesome!
  28. Practicing with print >>> print "Selena has", 2, "cats." Selena

    has 2 cats. >>> print 6+6, "eggs make a dozen." 12 eggs make a dozen. Try printing two sentences with numbers outside the quotes
  29. Saving Values Calculate a value: >>> 12 * 12 144

    How can you save that value, 144?
  30. Naming things Assign a name to a value: >>> number_of_donuts

    = 12 * 12 >>> favorite_color = "yellow"
  31. Naming things Assign a name to a value: number_of_donuts =

    12 * 12 favorite_color = "yellow" Variable name: number_of_donuts Value: 144 Variable name: favorite_color Value: "yellow"
  32. Naming things Assign a new value: favorite_color = "red" favorite_color

    = "brown" favorite_color = "fish + chips" favorite_color = 12 >>> favorite_color
  33. Naming things Assign a new value: favorite_color = "red" favorite_color

    = "brown" favorite_color = "fish + chips" favorite_color = 12 The meaning of the name is in you.
  34. Why Variables Rule Durability: calculate once, keep the result >>>

    number_of_donuts = 144 >>> number_of_donuts 144 >>> number_of_donuts + 12 156
  35. Why Variables Rule Flexibility: keep the name, change the value

    >>> number_of_donuts = 12 * 12 >>> number_of_donuts = number_of_donuts - 3 141
  36. Why Variables Rule Context: name a value to give it

    meaning >>> number_of_donuts = 12 * 12 >>> number_of_donuts 144 Now we know that number refers to donuts!
  37. Using print to output variables >>> eggs = 12 >>>

    "How many eggs? " + eggs Error >>> print "How many eggs?", eggs How many eggs? 12
  38. Variables Practice 1 >>> name = "Michelle" >>> color =

    "yellow" >>> print "My name is", name, "and my favorite color is", color >>> name = "Selena" >>> color = "Red" >>> print "My name is", name, "and my favorite color is", color
  39. Variables Practice 1: Answers >>> print "My name is", name,

    "and my favorite color is", color Output: My name is Michelle and my favorite color is yellow My name is Selena and my favorite color is red
  40. Variables Practice 2 >>> name = "Jason" >>> age =

    26 >>> dog_year_length = 7 >>> dog_years = age * dog_year_length >>> print name, "is", dog_years, "in dog years!"
  41. Variables Practice 3 Use decimal numbers if needed for precision:

    >>> age = 32 >>> decade = 10 >>> print "I've lived for", age / decade, "decades." >>> decade = 10.0 >>> print "I've lived for", age / decade, "decades."
  42. Variables Practice 3: Answers >>> print "I've lived for", age

    / decade, "decades." I've lived for 3 decades. I've lived for 3.2 decades.
  43. Tomorrow 9:30am: Check in, coffee, group warm up *** Bring

    your packet with you! *** Street parking is not free after 1pm!
  44. Exercise Set 1 Review Grab your Python shell and hold

    on to your hats, because here we go!
  45. Exercise Set 1 Review Store your name, height and favorite

    color in variables Print out (in a sentence) that information about yourself
  46. Exercise Set 1 Review Store your name, height and favorite

    color in variables Print that information out in a sentence >>> name = "Michelle" >>> height = "67" >>> color = "yellow" >>> print name, "is", height, "inches tall and loves", color
  47. Exercise Set 1 Review >>> print name, "is", height, "inches

    tall and loves", color, "!" Michelle is 67 inches tall and loves yellow!
  48. Exercise Set 1 Review Calculate the number of 2-week disposable

    contact packs you need in a year and store it in a variable. >>> contact_packs = 52 / 2
  49. Exercise Set 1 Review Print out the number of disposable

    contact packs you need to buy to be stocked for a year. Print a complete sentence. >>> print "I will need to buy", contact_packs, "contact packs this year." I will need to buy 26 contact packs this year.
  50. Exercise Set 1 Review Calculate how many seconds all attendees

    will spend in the workshop this weekend Store the value in a variable Print out the answer in a sentence
  51. Exercise Set 1 Review Calculate how many seconds all attendees

    will spend in the workshop this weekend Store the value in a variable >>>seconds = 10 * 60 * 60 * 32
  52. Exercise Set 1 Review Print out the answer in a

    sentence >>> print "Attendees will spend a total of", seconds, "seconds in the workshop." Attendees will spend a total of 1152000 seconds in the workshop.
  53. Exercise Set 1 Review Calculate the number of donuts made

    in a week if 15 dozen are made each day Print out (in a sentence) the number of donuts 100 people would have to eat eat in order to eat them all
  54. Exercise Set 1 Review Calculate the number of donuts made

    in a week if 15 dozen are made each day >>> number_of_dozens = 15 * 7
  55. Exercise Set 1 Review Print out (in a sentence) the

    number of donuts 100 people would have to eat eat in order to eat them all >>> print "Each person will eat", number_of_dozens * 12 / 100.0, "donuts." Each person will eat 12.6 donuts.
  56. Talking to Python: Strings >>> print 'Whoa' >>> print """Incredible!"""

    >>> print '''Who knew??''' >>> print "" (empty string)
  57. Talking to Python: Strings Length of a string: >>> len('Whoa')

    4 >>>len ('Supercalifragilisticexpialidocious') 34
  58. Strings: Indexes Each element has a position called an index.

    H e l l o 0 1 2 3 4 In Python, indexes start at 0 -- "zero-indexed".
  59. Talking to Python: Strings >>> my_string = "Hello" >>> print

    my_string[0] H >>> print my_string[4] o
  60. Strings: Indexes Rules: Each character's position in a string is

    its index. Indexes start at 0. Spaces inside the string are counted.
  61. Strings: Slicing Grabbing more than one character. H e l

    l o 0 1 2 3 4 >>> print my_string[1:4] 'ell'
  62. Strings: Slicing Note where the slice starts and ends: >>>

    print my_string[1:4] 'ell' H e l l o 0 1 2 3 4
  63. Strings: Slicing Practice >>> name = "Barbara Shaurette" >>> print

    name[0:7] Barbara Try printing part of your own name
  64. Strings: Slicing Tricks Leave off the starting index: >>> print

    name[:5] Barba Leave off the ending index: >>> print name[3:] bara What happens if you leave out both?
  65. Data Types Three types of data we already know about:

    "Hi!" string 27 integer 15.238 float
  66. Data Types Remember yesterday's concatenation error? >>> "Hi!" + 7

    TypeError: cannot concatenate 'str' and 'int' objects
  67. Data Types Python can tell us about types using type():

    >>> type("Hi!") <type 'str'> Can you get Python to output int and float types?
  68. Data Types Even type itself is an object, and has

    a type: >>> type(type) <type 'type'> The type of the type object is type. Whoa.
  69. Data Type: List List: a sequence of other objects >>>

    fruit = ["apple", "berry", "grape"] >>> numbers = [3, 17, -4, 8, 8, 3]
  70. Python Lists: Indexing Lists have indexes just like strings! >>>

    print fruit[0] apple >>> print fruit[2] grape >>> print fruit[3] Error
  71. Python Lists: Slicing Slice lists just like strings! chores =

    ['dishes', 'groceries', 'laundry', 'toilet'] >>> print chores[0:2] <- my chores >>> print chores[2:4] <- J's chores What are Jason's chores??
  72. Python Lists: Exercises Make a list of the four Beatles'

    Use an index to print your favorite one's name Split the band up using slice
  73. Data Type: Boolean A boolean value can be: True or

    False. Is 1 equal to 1? 1 == 1 ? True Is 15 less than 5? 15 < 5 ? False
  74. Comparison Operators == Equal to != Not equal to <

    Less than > Greater than <= Less than or equal to >= Greater than or equal to
  75. Comparison Practice Guess the answer, then try in Python shell:

    16 != 16 5 >= 6 5 < 4 + 3 12 + 1 >= 12 16 * 2 == 32
  76. Comparison Practice 16 != 16 False 5 >= 6 False

    5 < 4 + 3 True 12 + 1 >= 12 True 16 * 2 == 32 True
  77. Boolean Operators: and, or, not Combine comparisons: and: All must

    be correct to be True or: Only one must be correct to be True
  78. Boolean Operators: and and: All must be correct to be

    True 1 == 1 and 2 == 2 True and True --> True True and True --> True True and False --> False False and True --> False False and False --> False
  79. Boolean Operators: or or: Only one must be correct to

    be True 1 == 1 or 2 != 2 True or False --> True True or True --> True True or False --> True False or True --> True False or False --> False
  80. Boolean Operators: and, or, not not: reverse a Boolean value

    True becomes False False becomes True not 1 == 1 not True False
  81. Boolean Operators: Practice 1 == 1 and 2 == 2

    True and True ---> True 3 > 1 and 5 == 4 True and False ---> False 1 == 5 and 6 >= 5 False and True ---> False
  82. Boolean Operators: Practice 1 == 1 or 2 == 2

    True or True ---> True 3 > 1 or 5 == 4 True or False ---> True 1 == 5 or 6 >= 15 False or False ---> False
  83. Boolean Operators: Practice not 1 == 5 not False True

    ---> True not 3 > 1 not True False ---> False
  84. Boolean Operators: Practice 1 == 1 and not 1 ==

    5 True and not False True and True ---> True not 3 > 1 or 3 == 4 not True or False False or False ---> False
  85. The if statement If a condition is met, execute what

    follows. >>> name = "Michelle" >>> if name == "Michelle": ... print "Hi Michelle!" Hi Michelle!
  86. Adding More Choices "If you're not busy, let's eat lunch

    now. Or else we can eat in an hour." "If there's mint ice cream, I'll have a scoop. Or else I'll take butter pecan."
  87. The else clause >>> if name == "Michelle": ... print

    "Hi Michelle!" ... else: ... print "Impostor!"
  88. Including Many Options "If you're not busy, let's eat lunch

    now. Or else if Bob is free I will eat with Bob. Or else if Judy's around we'll grab a bite. Or else we can eat in an hour."
  89. The elif clause >>> if name == "Michelle": ... print

    "Hi Michelle!" ... elif name == "Emily": ... print "Yo Emily." ... else: ... print "Who ARE you?!"
  90. if/elif/else Practice Write an if statement that prints "Yay!" if

    the variable called color is equal to "yellow". Add an elif clause and an else clause to print two different messages under other circumstances.
  91. Getting to Know the Command Line Windows: bit.ly/cli-windows Mac OS

    X: bit.ly/cli-mac-os-x Linux: bit.ly/cli-linux
  92. 97 Simple Steps to a PB&J Is making PB&J difficult?

    How many steps does it feel like?
  93. 97 Simple Steps to a PB&J Are the inputs the

    same? Are the outputs the same? Do all steps get completed?
  94. 97 Simple Steps to a PB&J Which is easier: 1.

    Get bread 2. Get knife 4. Open PB 3. Put PB on knife 4. Spread PB on bread ... 1. Make PB&J
  95. Functions: Grouping Instructions What it's like in our minds: Make

    PB&J. In Python, it could be expressed as: make_pbj(bread, pb, jam, knife)
  96. Functions: Practice Let's create a function: >>> def say_hello(name): ...

    print "Hello", name Indent the second line 4 spaces. Hit enter until you see the prompt again.
  97. Functions: Practice def is a keyword we use to define

    a function. name is an input. def say_hello(name): print "Hello", name
  98. Functions: Practice Work alone or with a neighbor to create

    a function that doubles a number and prints it out.
  99. Functions: Practice Work alone or with a neighbor to create

    a function that doubles a number and prints it out. >>> def double_number(number): ... print number * 2 >>> double_number(14) 28
  100. Functions: Practice Work alone or with a neighbor to create

    a function that takes two numbers, multiplies them together, and prints out the result.
  101. Functions: Practice Work alone or with a neighbor to create

    a function that takes two numbers, multiplies them together, and prints out the result. >>> def multiply(num1, num2): ... print num1 * num2 >>> multiply(4, 5) 20
  102. Functions: Output print displays something to the screen. What if

    you want to save the value that results from a calculation, like your doubled number?
  103. Functions: Output >>> def double_number(number): ... print number * 2

    >>> new_number = double_number(12) 24 >>> new_number <-- empty variable >>>
  104. Functions: Output >>> def double_number(number): ... return number * 2

    >>> new_number = double_number(12) >>> new_number <-- value is 24 24
  105. Functions Rules: Functions are declared using def Functions are called

    using parentheses Functions take inputs and return outputs
  106. Functions Rules: print causes display, but no value is returned

    when the function is called return returns a value to the caller (you!)
  107. PDX Python Hack Night http://meetup.com/pdxpython Every Month: 3rd Wednesday After

    work: 6 - 9pm Beginner's Room with mentors Beer :) Hosted by Urban Airship: 11th + NW Flanders
  108. Additional Resources Learn Python the Hard Way http://learnpythonthehardway.org/book/ How to

    Think Like a Computer Scientist http://openbookproject.net/thinkcs/python/english2e/ Learn Python with Games http://inventwithpython.com/chapters/