Boston Python Workshop 3/Friday/Tutorial: Difference between revisions

m
Protected "Boston Python Workshop 3/Friday/Tutorial" ([edit=autoconfirmed] (indefinite) [move=autoconfirmed] (indefinite))
imported>Jesstess
imported>Jesstess
m (Protected "Boston Python Workshop 3/Friday/Tutorial" ([edit=autoconfirmed] (indefinite) [move=autoconfirmed] (indefinite)))
 
(107 intermediate revisions by 3 users not shown)
Line 1:
Welcome to the Friday tutorial!
Type each of the following expressions at the Python prompt (no copying and pasting! You'll learn the concepts better if you type them out yourself). After you type an expression, hit Return. This causes the Python interpreter to evaluate the expression.
 
This tutorial covers several core programming concepts that we'll build upon during an interactive lecture tomorrow morning. It will take 1-2 hours to complete. There's a break in the middle, and exercises at the middle and end to help review the material.
 
This is an interactive tutorial! As you go through this tutorial, any time you see something that looks like this:
 
<pre>
a = "Hello"
</pre>
 
you should type the expression at a Python prompt, hitting Return after every line and noting the output.
 
No copying and pasting! You'll learn the concepts better if you type them out yourself.
 
==Math==
 
[[File:Calculator.png|100px]]
 
Math in Python looks a lot like math you type into a calculator. A Python prompt makes a great calculator if you need to crunch some numbers and don't have a good calculator handy.
Line 33 ⟶ 47:
</pre>
 
Hey now! That last result is probably not what you expected. What's going on here is that integer divison produces an integer. You need a number that knows about the decimal point to get a decimal out of division:
 
<pre>
Line 45 ⟶ 59:
</pre>
 
What do you need to do to get the right answer? Use data types that understand decimals for each of the divisions:
 
<pre>
Line 52 ⟶ 66:
</pre>
 
The two previous expressions produce the same result. You only need to make one of the numbers in each fraction have a decimal. When the Python interpreter goes to do the division, it notices that one of the numbers in the fraction cares about decimals and says '"that means I have to make the other number care about decimals too".
 
===Modulus===
 
The modulus operator <code>%</code> gives you the remainder after division. For example, 6 % 3 returns 0 because 3 goes into 6 twice, with nothing left over. 5 % 3 returns 2, because 3 goes into 5 once, with 2 left over.
 
<pre>
10 % 2
10 % 3
10 % 4
10 % 5
</pre>
 
==Types==
 
[[File:Geometry.png|150px]]
There's a helpful function (more on what a function is in a second) called <code>type</code> that tells you what kind of thing -- what <b>data type</b> -- Python thinks something is. We can check for ourselves that Python considers '1' and '1.0' to be different data types:
 
There's a helpful <b>function</b> (more on what a function is in a second) called <code>type</code> that tells you what kind of thing -- what <b>data type</b> -- Python thinks something is. We can check for ourselves that Python considers '1' and '1.0' to be different data types:
 
<pre>
Line 63 ⟶ 90:
</pre>
 
So now we've seen two data types: <b>integers</b> and <b>floats</b>.
 
I used the term 'function' without explaining what it is -- we'll talk about functions amore lotin more ona Saturdaybit, and write our own, but for now know twothese things:
 
* Functions encapsulate some useful bit of work. We save that useful bit of work inside the function so we don't have to type it over and over again every time we want to use it. So, for example, some nice person decided that being able to determine the type of an object was useful, so he or she put the Python code that figures out an object's type into the function <code>type</code>, and now we all get to use it, instead of having to write it ourselves.
* To use a function, write the name of the function followed by an open parenthesis, possibly some data (we call that data the 'arguments' to the function), and then a close parenthesis.
* Functions are sort of like functions in math class. You provide input to a function and it produces output. The <code>type</code> function takes data as an input, and produces what type of data the data is (e.g. an integer or a float) as output.
* To use a function, write the name of the function followed by an open parenthesis, what the function takes as input (we call that input the <b>arguments</b> to the function), and then a close parenthesis.
 
So in this case 'type' is the name of the function, and it takes one argument; in the example we first give <code>type</code> an argument of 1 and then give it an argument of 1.0.
 
* Functions are a lot like functions in math class. You provide input to a function, and it possibly produces output. The <code>type</code> function takes data as an input, and produces what type of data the data is (e.g. an integer or a float) as output.
 
===Command history===
 
Stop here and try hitting the Up arrow on your keyboard a few times. The Python <b>interpreter</b> saves a history of what you've entered, so you can arrow up to old commands and hit Return to re-run them!
 
==Variables==
 
[[File:Fraction.png|100px]]
 
A lot of work gets done in Python using variables. Variables are a lot like the variables in math class, except that in Python variables can be of any data type, not just numbers.
Line 95 ⟶ 124:
<code>magic_number = 1500</code><br />
<code>amountOfFlour = .75</code><br />
<code>divisible_by_6my_name = 54"Jessica"</code>
 
Projects develop naming conventions: maybe multi-word variable names use underscores (like <code>magic_number</code>), or "camel case" (like <code>amountOfFlour</code>). The most
Line 101 ⟶ 130:
 
==Output==
 
[[File:Pacman.png|100px]]
 
Notice how if you type a 4 and hit enter, the Python interpreter spits a 4 back
Line 142 ⟶ 173:
</pre>
 
Note that the spacing doesn't matter.:
 
<pre>
Line 154 ⟶ 185:
</pre>
 
are both valid Python <b>syntax</b>and mean the same thing.
 
<pre>
Line 166 ⟶ 197:
</pre>
 
are also both valid syntaxand mean the same thing. You should strive to be consistent with whatever syntaxspacing you like or a job requires, since it makes reading the code easier.
 
You aren't cheating and skipping typing these exercises out, are you? Good! :)
 
==Strings==
 
[[File:Letter.png|100px]]
 
So far we've seen two data types: <b>integers</b> and <b>floats</b>. Another useful data type is a <b>string</b>, which is just what Python calls a bunch of characters (like numbers, letters, whitespace, and punctuation) put together. Strings are indicated by being surrounded by quotes:
 
<pre>
print "Hello"
print "Python, I'm your #1 fan!"
</pre>
 
Like with the math data types above, we can use the <code>type</code> function to check the type of strings:
 
<pre>
type("Hello")
type(1)
type("1")
</pre>
 
Line 180 ⟶ 223:
 
<pre>
print "Hello" + "World"
print "Hello", "World"
</pre>
 
<pre>
name = "Jessica"
print "Hello " + name
</pre>
 
===Printing===
 
You can print strings using <code>print</code>:
 
<pre>
Line 192 ⟶ 243:
 
<pre>
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print my_string
</pre>
 
How about printing different data types together?
Like with the math data types above, we can use the <code>type</code> function to check the type of these strings:
 
<pre>
type("Hello")
type(1)
type("1")
</pre>
 
Printing different data types together
 
<pre>
Line 211 ⟶ 254:
</pre>
 
Hey now! The output from the previous example iswas really different and interesting; let's break down exactly what is happeninghappened:
 
<code>>>> print "Hello" + 1</code><br />
Line 248 ⟶ 291:
</pre>
 
Python is actually turning the integer 1 into a string before printing, and that's why thethat concatenation works: Python does know how to concatenate two strings.
 
We can convert an integer into a string ourselves, using the <code>str</code> function:
Line 256 ⟶ 299:
</pre>
 
Like the <code>type</code> function from before, the <code>str</code> function takes 1 argument,. inIn the above example it took the integer 1. <code>str</code> takes ina Python object as input and produces a string version of that input as output.
 
===String length===
 
There's another useful function that works on strings called <code>len</code>. <code>len</code> returns the length of a string as an integer:
 
<pre>
print len("Hello")
print len("")
fish = "humuhumunukunukuapuaʻa"
print fish, "is a Hawaiian fish whose name is", len(fish), "characters long."
</pre>
 
===Quotes===
Line 275 ⟶ 329:
</pre>
 
This gives us another <b>traceback</b>, for a new kind of error, a <code>SyntaxError</code>. When Python looks at that expression, it sees the string 'I' and then
 
<code>m a happy camper'</code>
Line 290 ⟶ 344:
 
<pre>
print 'I\'m a happy camper'
print 'Ada Lovelace is often called the world\'s first programmer.'
print "Computer scientist Grace Hopper popularized the term \"debugging\"."
Line 305 ⟶ 360:
 
==Part 1 Practice==
 
[[File:Detective.png|100px]]
 
Read the following expressions, but don't execute them. Guess what the output will be. After you've made a guess, copy and paste the expressions at a Python prompt and check your guess.
Line 349 ⟶ 406:
==End of Part 1==
 
Congratulations! You've learned about and practiced math, strings, variables, data types, exceptions, tracebacks, and executing Python from the Python prompt and from a file.
 
Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material.
 
==Python scripts==
 
[[File:Treasure_map.png|100px]]
 
Until now we've been executing commands at the Python prompt. This is great for math, short bits of code, and testing. For longer ideas, it's easier to store the code in a file.
 
<ol>
<li>Download the file http://mit.edu/jesstess/www/BostonPythonWorkshop2BostonPythonWorkshop3/nobel.py. The ".py" extension hints that this is a Python script.</li>
<li>Save the file in your Desktop directory.</li>
<li>Open a command prompt, and use the navigation commands (<code>dir</code> and <code>cd</code> on Windows, <code>ls</code>, <code>pwd</code>, and <code>cd</code> on OS X and Linux) to navigate to your home directory. See [[Boston Python Workshop 3/Friday#Goal_.234:_practice_navigating_the_computer_from_a_command_prompt|navigating from a command prompt]] for a refresher on those commands.</li>
Line 381 ⟶ 440:
<li>How do you print a multi-line string so that whitespace is preserved?</li>
</ol>
 
Let's get back to some interactive examples. Keep typing them out! You'll thank yourself tomorrow. :)
 
==Booleans==
 
[[File:Scales.png|100px]]
So far, the code we've written has been <i>unconditional</i>: no choice is getting made, and the code is always run. Python has another data type called a <b>boolean</b> that is helpful for writing code that makes decisions. There are two booleans: <code>True</code> and <code>False</code>:
 
So far, the code we've written has been <i>unconditional</i>: no choice is getting made, and the code is always run. Python has another data type called a <b>boolean</b> that is helpful for writing code that makes decisions. There are two booleans: <code>True</code> and <code>False</code>.
 
<pre>
Line 402 ⟶ 465:
</pre>
 
You can test if Python objects are equal or unequal. The result is a boolean:
 
<pre>
Line 426 ⟶ 489:
</pre>
 
<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class. The result of these tests is a boolean:
 
<pre>
Line 444 ⟶ 507:
</pre>
 
You can check for containment with the <code>in</code> keyword, which also results in a boolean:
 
<pre>
Line 465 ⟶ 528:
 
==Flow Control==
 
[[File:Fork.png|100px]]
 
====if statements====
Line 477 ⟶ 542:
That was our first multi-line piece of code, and the way to enter it at a Python prompt is a little different. First, type the <code>if True:</code> part, and hit enter. The next line will have <code>...</code> as a prompt, instead of the usual <code>&gt;&gt;&gt;</code>. This is Python telling us that we are in the middle of a <b>code block</b>, and so long as we indent our code it should be a part of this code block.
 
Type 4 spaces, and then type <code>print "I'm True!"</code>. Hit enter to end the line, and hit enter again to tell Python you are done with this code block. All together, it will look something like this:
 
<pre>
Line 517 ⟶ 582:
In summary, things that represent emptyness or zeroness, including the boolean <code>False</code>, empty string, and 0, will evaluate to <code>False</code> in a conditional expression. Everything else, including the boolean <code>True</code>, non-empty strings, and numbers other than 0, is <code>True</code>.
 
====more choices: <code>if</code> and <code>else</code>====
 
You can use the <code>else</code> keyword to conditionally execute code only when the expression for the <code>if</code> blockexpression isn't trueTrue:
 
<pre>
Line 525 ⟶ 590:
brother_age = 12
if sister_age > brother_age:
print "Sistersister is older"
else:
print "brother is older"
</pre>
 
Like with <code>if</code>, the code block under the <code>else</code> statement must be indented so Python knows that it is a part of the <code>else</code> block.
 
====compound conditionals: <code>and</code> and <code>or</code>====
You can check multiple expressions together using the <code>and</code> and <code>or</code> keywords. If two expressions are joined by an <code>and</code>, they <b>both</b> have to be True for the overall expression to be True. If two expressions are joined by an <code>or</code>, as long as <b>one</b> is True, the overall expression is True.
 
You can check multiple expressions together using the <code>and</code> and <code>or</code> keywords. If two expressions are joined by an <code>and</code>, they <b>both</b> have to be True for the overall expression to be True. If two expressions are joined by an <code>or</code>, as long as <b>at least one</b> is True, the overall expression is True.
 
<pre>
Line 549 ⟶ 616:
1 <= 0 or "a" not in "abc"
</pre>
 
Guess what will happen when you enter these next two examples, and then type them out and see if you are correct. If you have trouble with the indenting, call over a staff member and practice together. It is important to be comfortable with indenting for tomorrow.
 
<pre>
Line 568 ⟶ 637:
</pre>
 
You can have as many lines of code as you want in <code>if</code> and <code>else</code> blocks; just make sure to indent them so Python knows they are a part of the block.
 
====even more choices: <code>elif</code>====
 
If you have more than two cases, you can use the <code>elif</code> keyword to check more cases. You can have as many <code>elif</code> cases as you want; Python will go down the code checking each <code>elif</code> until it finds a True condition or reaches the default <code>else</code> block.
 
<pre>
sister_age = 15
brother_age = 12
if sister_age > brother_age:
print "sister is older"
elif sister_age == brother_age:
print "sister and brother are the same age"
else:
print "brother is older"
</pre>
 
You don't have to have an <code>else</code> block, if you don't need it. That just means there isn't default code to execute when none of the <code>if</code> or <code>elif</code> conditions are True:
 
<pre>
color = "orange"
if color == "green" or color == "red":
print "Christmas color!"
elif color == "black" or color == "orange":
print "Halloween color!"
elif color == "pink":
print "Valentine's Day color!"
</pre>
 
If color had been "purple", that code wouldn't have printed anything.
 
==Writing Functions==
 
[[File:Quill.png|100px]]
 
We talked a bit about functions when we introduced the <code>type()</code> function. Let's review what we know about functions:
 
* They do some useful bit of work.
* They let us re-use code without having to type it out each time.
* They take input and possibly produce output (we say they <b>return</b> a value). You can assign a variable to this output.
* You call a function by using its name followed by its <b>arguments</b> in parenthesis.
 
For example:
 
<pre>
length = len("Mississippi")
</pre>
 
Executing this code assigns the length of the string "Mississippi" to the variable <code>length</code>.
 
We can write our own functions to encapsulate bits of useful work so we can reuse them. Here's how you do it:
 
<b>Step 1: write a function signature</b>
 
A <b>function signature</b> tells you how the function will be called. It starts with the keyword <code>def</code>, which tells Python that you are defining a function. Then comes a space, the name of your function, an open parenthesis, the comma-separated input <b>parameters</b> for your function, a close parenthesis, and a colon. Here's what a function signature looks like for a function that takes no arguments:
 
<code>def myFunction():</code>
 
Here's what a function signature looks like for a function that takes one argument called <code>string</code>:
 
<code>def myFunction(string):</code>
 
And one for a function that takes two arguments:
 
<code>def myFunction(myList, myInteger):</code>
 
Parameters should have names that usefully describe what they are used for in the function.
 
We've used the words <b>parameters</b> and <b>arguments</b> seemingly interchangeably to reference the input to functions. The distinction isn't really important right now, but if you're curious: in function signatures the input is called parameters, and when you are calling the function the input is called arguments.
 
<b>Step 2: do useful work inside the function</b>
 
Underneath the function signature you do your useful work. Everything inside the function is indented, just like with if/else blocks, so Python knows that it is a part of the function.
 
You can use the variables passed into the function as parameters, just like you can use variables once you define them outside of functions.
 
<pre>
def add(x, y):
result = x + y
</pre>
 
<b>Step 3: return something</b>
 
If you want to be able to assign a variable to the output of a function, the function has to <b>return that output</b> using the <code>return</code> keyword.
 
<pre>
def add(x, y):
result = x + y
return result
</pre>
 
or, even shorter:
 
<pre>
def add(x, y):
return x + y
</pre>
 
You can return any Python object: numbers, strings, booleans ... even other functions!
 
Once you execute a return, you are done with the function -- you don't get to do any more work. That means if you have a function like this:
 
<pre>
def absoluteValue(number):
if number < 0:
return number * -1
return number
</pre>
 
if <code>number</code> is less than 0, you return <code>number * -1</code> and never even get to the last line of the function. However, if <code>number</code> is greater than or equal to 0, the <code>if</code> expression evaluates to <code>False</code>, so we skip the code in the <code>if</code> block and return <code>number</code>.
 
We could have written the above function like this if we wanted. It's the same logic, just more typing:
 
<pre>
def absoluteValue(number):
if number < 0:
return number * -1
else:
return number
</pre>
 
<b>Step 4: use the function</b>
 
Once you define a function you can use it as many times as you want:
 
<pre>
def add(x, y):
return x + y
 
result = add(1234, 5678)
print result
result = add(-1.5, .5)
print result
</pre>
 
Functions don't have to return anything, if you don't want them to. They usually return something because we usually want to be able to assign variables to their output.
 
==Part 2 Practice==
 
[[File:Detective.png|100px]]
 
Learning about functions opens up a whole new way for us to practice, using the programming site [http://codingbat.com codingbat.com]. The big goal of this practice section is to get you thinking about how to solve problems in Python.
 
Please visit http://codingbat.com/home/jessica.mckellar@gmail.com/Friday to complete the practice problems. You don't have to create a CodingBat account to do the exercises, but if you do create an account it'll keep track of which problems you've completed and other statistics.
 
==End of Part 2==
 
Congratulations! You've learned about and practiced executing Python scripts, booleans, conditionals, and if/else blocks, and you've written your own Python functions. This is a huge, huge accomplishment!
 
[[File:Champagne.png|100px]][[File:Party.png|125px]]
 
 
Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material. All that's left today is to get checked off, and we'll pick up with more Python fundamentals tomorrow morning.
 
[[Boston Python Workshop 3/Friday|&laquo; Back to the Friday Workshop page]]
Anonymous user