Editing Boston Python Workshop 3/Friday/Tutorial

Jump to navigation Jump to search

Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then save the changes below to finish undoing the edit.

Latest revision Your text
Line 47: Line 47:
 
</pre>
 
</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:
+
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>
 
<pre>
Line 59: Line 59:
 
</pre>
 
</pre>
  
What do you need to do to get the right answer? Use data types that understand decimals for each of the divisions:
+
What do you need to do to get the right answer? Use data types that understand decimals:
  
 
<pre>
 
<pre>
Line 66: Line 66:
 
</pre>
 
</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".
+
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===
 
===Modulus===
Line 94: Line 94:
 
I used the term 'function' without explaining what it is -- we'll talk about functions more in a bit, and write our own, but for now know these things:
 
I used the term 'function' without explaining what it is -- we'll talk about functions more in a bit, and write our own, but for now know these 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.
+
* Functions do 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.
* 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.
+
* Functions are a lot 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.
 
* 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.
  
Line 102: Line 102:
 
===Command history===
 
===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!
+
Stop here and try hitting the Up arrow on your keyboard. 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==
 
==Variables==
Line 208: Line 208:
  
 
<pre>
 
<pre>
"Hello"
+
print "Hello"
"Python, I'm your #1 fan!"
+
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>
 
</pre>
  
Line 223: Line 215:
  
 
<pre>
 
<pre>
"Hello" + "World"
+
print "Hello" + "World"
 +
print "Hello", "World"
 
</pre>
 
</pre>
 
<pre>
 
name = "Jessica"
 
print "Hello " + name
 
</pre>
 
 
===Printing===
 
 
You can print strings using <code>print</code>:
 
  
 
<pre>
 
<pre>
Line 245: Line 229:
 
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
 
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
 
print my_string
 
print my_string
 +
</pre>
 +
 +
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>
 
</pre>
  
Line 291: Line 283:
 
</pre>
 
</pre>
  
Python is actually turning the integer 1 into a string before printing, and that's why that concatenation works: Python does know how to concatenate two strings.
+
Python is actually turning the integer 1 into a string before printing, and that's why the 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:
 
We can convert an integer into a string ourselves, using the <code>str</code> function:
Line 299: Line 291:
 
</pre>
 
</pre>
  
Like the <code>type</code> function from before, the <code>str</code> function takes 1 argument. In the above example it took the integer 1. <code>str</code> takes a Python object as input and produces a string version of that input as output.
+
Like the <code>type</code> function from before, the <code>str</code> function takes 1 argument. In the above example it took the integer 1. <code>str</code> takes in a Python object as input and produces a string version of that input as output.
  
===String length===
+
====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:
 
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:
Line 329: Line 321:
 
</pre>
 
</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
+
This gives us another traceback, 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>
 
<code>m a happy camper'</code>
Line 344: Line 336:
  
 
<pre>
 
<pre>
print 'I\'m a happy camper'
 
 
print 'Ada Lovelace is often called the world\'s first programmer.'
 
print 'Ada Lovelace is often called the world\'s first programmer.'
 
print "Computer scientist Grace Hopper popularized the term \"debugging\"."
 
print "Computer scientist Grace Hopper popularized the term \"debugging\"."
Line 447: Line 438:
 
[[File:Scales.png|100px]]
 
[[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>
 
<pre>
Line 465: Line 456:
 
</pre>
 
</pre>
  
You can test if Python objects are equal or unequal. The result is a boolean:
+
You can test if Python objects are equal or unequal:
  
 
<pre>
 
<pre>
Line 489: Line 480:
 
</pre>
 
</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:
+
<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class:
  
 
<pre>
 
<pre>
Line 507: Line 498:
 
</pre>
 
</pre>
  
You can check for containment with the <code>in</code> keyword, which also results in a boolean:
+
You can check for containment with the <code>in</code> keyword:
  
 
<pre>
 
<pre>
Line 542: Line 533:
 
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.
 
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 like this:
+
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>
 
<pre>
Line 584: Line 575:
 
====more choices: <code>if</code> and <code>else</code>====
 
====more choices: <code>if</code> and <code>else</code>====
  
You can use the <code>else</code> keyword to execute code only when the <code>if</code> expression isn't True:
+
You can use the <code>else</code> keyword to execute code only when the <code>if</code> expression isn't true:
  
 
<pre>
 
<pre>
Line 595: Line 586:
 
</pre>
 
</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.
+
Like with <code>if</code>, the code block under the <code>else</code> statement must be indented.
  
 
====compound conditionals: <code>and</code> and <code>or</code>====
 
====compound conditionals: <code>and</code> and <code>or</code>====
Line 636: Line 627:
 
     print "Can I interest you in some choice gouda?"
 
     print "Can I interest you in some choice gouda?"
 
</pre>
 
</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>====
 
====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.
+
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> condition until it finds a true condition or reaches the default <code>else</code> block.
  
 
<pre>
 
<pre>
Line 654: Line 643:
 
</pre>
 
</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:
+
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 cases match:
  
 
<pre>
 
<pre>
Line 666: Line 655:
 
</pre>
 
</pre>
  
If color had been "purple", that code wouldn't have printed anything.
+
If color had been "purple", that code just wouldn't have printed anything.
  
 
==Writing Functions==
 
==Writing Functions==
Line 677: Line 666:
 
* They let us re-use code without having to type it out each time.
 
* 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.
 
* 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.
+
* You call a function by using its name followed by the input in parenthesis.
  
 
For example:
 
For example:
Line 685: Line 674:
 
</pre>
 
</pre>
  
Executing this code assigns the length of the string "Mississippi" to the variable <code>length</code>.
+
Running this 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:
 
We can write our own functions to encapsulate bits of useful work so we can reuse them. Here's how you do it:
Line 691: Line 680:
 
<b>Step 1: write a function signature</b>
 
<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:
+
A <b>function signature</b> tells you how the function will be called. It starts with the keyword <code>def</code>, which tells Python you are defining a function. Then comes a space, the name of your function, an open parenthesis, the comma-separated <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>
+
<pre>
 +
def myFunction():
 +
</pre>
  
 
Here's what a function signature looks like for a function that takes one argument called <code>string</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>
+
<pre>
 +
def myFunction(string):
 +
</pre>
  
 
And one for a function that takes two arguments:
 
And one for a function that takes two arguments:
  
<code>def myFunction(myList, myInteger):</code>
+
<pre>
 +
def myFunction(myList, myInteger):
 +
</pre>
  
 
Parameters should have names that usefully describe what they are used for in the function.
 
Parameters should have names that usefully describe what they are used for in the function.
Line 746: Line 741:
 
</pre>
 
</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>.
+
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 conditional for the if block evaluates to <code>False</code>, so we skip the code in the if block and <code>return number</code>. We could have written the above function like this if we wanted. It's the same logic, just more typing:
 
 
We could have written the above function like this if we wanted. It's the same logic, just more typing:
 
  
 
<pre>
 
<pre>
Line 780: Line 773:
 
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.
 
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.
+
[codingbat questions TBD]
  
 
==End of Part 2==
 
==End of Part 2==

Please note that all contributions to OpenHatch wiki are considered to be released under the Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) (see OpenHatch wiki:Copyrights for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource. Do not submit copyrighted work without permission!

Cancel Editing help (opens in new window)