Share
Embed
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.
Hacking Medusa
July 28, 2012
Transcript
156 slides
-
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! -
Meet your Mentors Selena Deckelmann Kevin Turner Amy Farrell Barbara
Shaurette Emily Strickland Jason Grlicky -
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 -
What to Expect Lessons in Python Pairing with neighbors Group
activities Lots of practice Checks for understanding Fun! :) -
What to Expect * Quick assessment * People Bingo! *
What is Programming? * Start speaking Python! -
What is a Computer? "A machine that stores and manipulates
information under the control of a changeable program." - John Zelle, Python Programming -
What is a Computer Program? "A detailed step-by-step set of
instructions telling a computer exactly what to do." - John Zelle, Python Programming -
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 -
Language complexity “I saw the man in the park with
the telescope.” -
Syntax "...the study of the principles and processes by which
sentences are constructed in particular languages". - Noam Chomsky (from Wikipedia) -
The Python Interactive Shell a.k.a. Python Interactive Interpreter, Python shell
Easy to use Instant feedback The prompt - prompts you to type stuff: >>> -
Talking to Python: Numbers Arithmetic operators: addition: + subtraction: -
multiplication: * Try doing some math in the interpreter: >>> 1 + 1 >>> 12 - 3 >>> 6 * 5 -
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? -
Talking to Python: Numbers Integers: 9 -55 Floats (have decimals):
17.318 10.0 Try typing an integer and a float -
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 -
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 -
Talking to Python: Strings >>> "apple" >>> "garlic breath" >>>
"Thanks for coming!" Try typing one without quotes: >>> apple What's the result? -
Interlude: Errors Errors are no problem... they are essential! Python
is trying to help. :) Let's make some errors: >>> apple >>> "baloney >>> Fun!" -
Talking to Python: Strings Rule: If it's a string, it
must be in quotes "apple" "garlic breath" "Thanks for coming!" -
Talking to Python: Strings addition is concatenation: + Try concatenating
(adding together strings): >>> "Hi" + "there!" 'Hithere' -
Talking to Python: Strings multiplication: * Try multiplying: >>> "HAHA"
* 250 Even better: >>> "BWA" + "HAHA" * 250 -
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 -
Talking to Python >>> 5 + 10 15 >>> "Three"
+ "Seven" + "Nine" 'ThreeSevenNine' -
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 -
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 -
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! -
Working Around Errors We want to display: How many eggs?
12 >>>"How many eggs? " + 12 Error Concatenation won't work. -
Working Around Errors print command is for display: >>> print
"How many eggs?", 12 How many eggs? 12 No concatenation, no problem! -
The print statement Note the differences in syntax: >>>"How many
eggs? " + 12 Error >>>print "How many eggs?", 12 How many eggs? 12 -
The print statement is handy You get spaces between items:
>>>"This" + "isn't" + "great." Thisisn'tgreat. >>>print "This", "is", "awesome!" This is awesome! -
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 -
Saving Values Calculate a value: >>> 12 * 12 144
How can you save that value, 144? -
Naming things Assign a name to a value: >>> number_of_donuts
= 12 * 12 >>> favorite_color = "yellow" -
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" -
Naming things Assign a new value: favorite_color = "red" favorite_color
= "brown" favorite_color = "fish + chips" favorite_color = 12 >>> favorite_color -
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. -
Why Variables Rule Durability: calculate once, keep the result >>>
number_of_donuts = 144 >>> number_of_donuts 144 >>> number_of_donuts + 12 156 -
Why Variables Rule Flexibility: keep the name, change the value
>>> number_of_donuts = 12 * 12 >>> number_of_donuts = number_of_donuts - 3 141 -
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! -
Using print to output variables >>> eggs = 12 >>>
"How many eggs? " + eggs Error >>> print "How many eggs?", eggs How many eggs? 12 -
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 -
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 -
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!" -
Variables Practice 2: Answers >>> print name, "is", dog_years, "in
dog years!" Jason is 182 in dog years! -
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." -
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. -
Tomorrow 9:30am: Check in, coffee, group warm up *** Bring
your packet with you! *** Street parking is not free after 1pm! -
Exercise Set 1 Review Grab your Python shell and hold
on to your hats, because here we go! -
Exercise Set 1 Review Store your name, height and favorite
color in variables Print out (in a sentence) that information about yourself -
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 -
Exercise Set 1 Review >>> print name, "is", height, "inches
tall and loves", color, "!" Michelle is 67 inches tall and loves yellow! -
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 -
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. -
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 -
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 -
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. -
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 -
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 -
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. -
Talking to Python: Strings "Python rules!" "chicken salad" "Jason will
be 27 next week." -
Talking to Python: Strings >>> print 'Whoa' >>> print """Incredible!"""
>>> print '''Who knew??''' >>> print "" (empty string) -
Talking to Python: Strings Length of a string: >>> len('Whoa')
4 >>>len ('Supercalifragilisticexpialidocious') 34 -
Strings: Indexes Strings are made up of character elements: >>>
"H" + "e" + "l" + "l" + "o" 'Hello' -
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". -
Talking to Python: Strings >>> my_string = "Hello" >>> print
my_string[0] H >>> print my_string[4] o -
Strings: Indexing Practice >>>my_string = "Hey, Bob!" >>>my_number = 6
>>>print my_string[my_number] o -
Strings: Indexing Practice >>>my_string = "Hey, Bob!" >>>my_number = 6
>>>print my_string[my_number - 1] B -
Strings: Indexes Rules: Each character's position in a string is
its index. Indexes start at 0. Spaces inside the string are counted. -
Strings: Slicing Grabbing more than one character. H e l
l o 0 1 2 3 4 >>> print my_string[1:4] 'ell' -
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 -
Strings: Slicing Practice >>> name = "Barbara Shaurette" >>> print
name[0:7] Barbara Try printing part of your own name -
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? -
Strings: Slicing Tricks Use variables: >>> start, end = 4,
7 >>> print name[start:end] ara -
Data Types Three types of data we already know about:
"Hi!" string 27 integer 15.238 float -
Data Types Remember yesterday's concatenation error? >>> "Hi!" + 7
TypeError: cannot concatenate 'str' and 'int' objects -
Data Types Python can tell us about types using type():
>>> type("Hi!") <type 'str'> Can you get Python to output int and float types? -
Data Types Rule: Every object has a type. Everything in
Python is an object! -
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. -
Data Type: List List: a sequence of other objects >>>
fruit = ["apple", "berry", "grape"] >>> numbers = [3, 17, -4, 8, 8, 3] -
Python Lists: Indexing Lists have indexes just like strings! >>>
print fruit[0] apple >>> print fruit[2] grape >>> print fruit[3] Error -
Python Lists: Exercises >>> fruit ['apple', 'berry', 'grape'] Use type()
to verify the type of each element -
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?? -
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 -
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 -
Comparison Operators == Equal to != Not equal to <
Less than > Greater than <= Less than or equal to >= Greater than or equal to -
Comparison Practice >>> 1 == 2 >>> 1 < 2
>>> 1 != 2 -
Comparison Practice >>> 1 != 2 >>> 1 + 1
== 2 >>> 3 - 2 > 2 -
Comparison Practice Guess the answer, then try in Python shell:
16 != 16 5 >= 6 5 < 4 + 3 12 + 1 >= 12 16 * 2 == 32 -
Comparison Practice 16 != 16 False 5 >= 6 False
5 < 4 + 3 True 12 + 1 >= 12 True 16 * 2 == 32 True -
Boolean Operators: and, or, not Combine comparisons: and: All must
be correct to be True or: Only one must be correct to be True -
Boolean Operators: and, or, not Reverse a Boolean: not: True
becomes False False becomes True -
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 -
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 -
Boolean Operators: and, or, not not: reverse a Boolean value
True becomes False False becomes True not 1 == 1 not True False -
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 -
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 -
Boolean Operators: Practice not 1 == 5 not False True
---> True not 3 > 1 not True False ---> False -
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 -
Boolean Operators: Practice Try these with your neighbor: http://bit.ly/boolean-practice Switch
to your neighbor's keyboard after 10! -
Making Decisions "If you're not busy, let's eat lunch now."
"If the trash is full, go empty it." -
The if statement If a condition is met, execute what
follows. >>> name = "Michelle" >>> if name == "Michelle": ... print "Hi Michelle!" Hi Michelle! -
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." -
The else clause >>> if name == "Michelle": ... print
"Hi Michelle!" ... else: ... print "Impostor!" -
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." -
The elif clause >>> if name == "Michelle": ... print
"Hi Michelle!" ... elif name == "Emily": ... print "Yo Emily." ... else: ... print "Who ARE you?!" -
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. -
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 -
97 Simple Steps to a PB&J Is making PB&J difficult?
How many steps does it feel like? -
97 Simple Steps to a PB&J Are the inputs the
same? Are the outputs the same? Do all steps get completed? -
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 -
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) -
Functions: Grouping Instructions make_pbj(bread, pb, jam, knife) Python function name:
make_pbj Inputs to the function: bread, pb, jam, knife -
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. -
Functions: Practice Now we'll call the function: >>> say_hello("Michelle") Hello,
Michelle >>> say_hello("Selena") Hello, Selena -
Functions: Practice Use your new function to say hello to
all the members on your team! -
Functions: Practice def is a keyword we use to define
a function. name is an input. def say_hello(name): print "Hello", name -
Functions: Practice Work alone or with a neighbor to create
a function that doubles a number and prints it out. -
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 -
Functions: Practice Work alone or with a neighbor to create
a function that takes two numbers, multiplies them together, and prints out the result. -
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 -
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? -
Functions: Output >>> def double_number(number): ... print number * 2
>>> new_number = double_number(12) 24 >>> new_number <-- empty variable >>> -
Functions: Output >>> def double_number(number): ... return number * 2
>>> new_number = double_number(12) >>> new_number <-- value is 24 24 -
Functions Rules: Functions are declared using def Functions are called
using parentheses Functions take inputs and return outputs -
Functions Rules: print causes display, but no value is returned
when the function is called return returns a value to the caller (you!) -
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 -
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/