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

imported>Jesstess
 
(25 intermediate revisions by 2 users not shown)
Line 81:
So now we've seen two data types: <b>integers</b> and <b>floats</b>.
 
By the way, what is a "function"? Here are the important ideas about functions:
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:
 
* A function encapsulates a useful bit of work and gives that work a name.
* 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 are sort of like functions in math class. You provide input to a function and it produces output. TheFor example, 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, then what the function takesneeds as input (we call that input the <b>arguments</b> to the function), and then a close parenthesis.
* Programmers have a lot of slang around functions. They'll say that functions "take" arguments, or that they "give" or "pass" arguments to a function. "call" and "invoke" are both synonyms for using a function.
 
SoIn inthe thisexample caseabove, '"type'" iswas the name of the function,. and it<code>type</code> takes one argument; in the example we first givegave <code>type</code> an argument of 1 and then givegave it an argument of 1.0.
 
==== Diagram of "calling" a function ====
 
[[File:Function_diagram.png]]
 
===Command history===
Line 219 ⟶ 224:
<pre>
name = "Jessica"
print "Hello " + name
</pre>
 
How about concatenating different data types?
===Printing===
 
You can print strings using <code>print</code>:
 
<pre>
h = "Hello"
w = "World"
print h + w
</pre>
 
<pre>
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print my_string
</pre>
 
How about printing different data types together?
 
<pre>
print "Hello" + 1
</pre>
 
Hey now! The output from the previous example was really different and interesting; let's break down exactly what happened:
 
<code>>>> print "Hello" + 1</code><br />
<code>Traceback (most recent call last):</code><br />
<code> File "<stdin>", line 1, in <module></code><br />
Line 261 ⟶ 251:
 
<pre>
print "Hello" + "World"
</pre>
 
Line 269 ⟶ 259:
 
<pre>
print "Hello" + 1
</pre>
 
Line 277 ⟶ 267:
 
<pre>
print "Hello" + str(1)
</pre>
 
Line 287 ⟶ 277:
 
<pre>
print len("Hello")
print len("")
fish = "humuhumunukunukuapuaʻa"
lengthname_length = str(len(fish))
print fish + " is a Hawaiian fish whose name is " + lengthstr(name_length) + " characters long."
</pre>
 
Line 299 ⟶ 289:
 
<pre>
print 'Hello'
print "Hello"
</pre>
 
Line 308 ⟶ 298:
 
<pre>
print 'I'm a happy camper'
</pre>
 
Line 320 ⟶ 310:
 
<pre>
print "I'm a happy camper"
</pre>
 
Line 326 ⟶ 316:
 
<pre>
print "A" * 40
print "ABC" * 12
h = "Happy"
b = "Birthday"
print (h + b) * 10
</pre>
 
Line 342 ⟶ 332:
<pre>
total = 1.5 - 1/2
print total
type(total)
</pre>
Line 351 ⟶ 341:
b = "brown"
c = "fox jumps over the lazy dog"
print "The " + a * 3 + " " + b * 3 + " " + c
</pre>
 
Line 359 ⟶ 349:
 
Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material.
 
[[File:Fireworks.png|200px]]
 
== Part 2: Printing==
 
So far we've been learning at the interactive <b>Python interpreter</b>. When you are working at the interpreter, any work that you do gets printed to the screen. For example:
 
<pre>
h = "Hello"
w = "World"
h + w
</pre>
 
will display "HelloWorld".
 
Another place that we will be writing Python code is in a file. When we run Python code from a file instead of interactively, we don't get work printed to the screen for free. We have to tell Python to print the information to the screen. The way we do this is with the <b>print</b> function. Here's how it works:
 
<pre>
h = "Hello"
w = "World"
print(h + w)
</pre>
 
<pre>
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print(my_string)
</pre>
 
The string manipulate is exactly the same as before. The only difference is that you need to use <b>print</b> to print results to the screen:
 
<code>h + w</code>
 
becomes
 
<code>print(h + w)</code>
 
We'll see more examples of the print function in the next section.
 
==Python scripts==
Line 364 ⟶ 391:
[[File:Treasure_map.png|100px]]
 
Until now we've been executingusing commandsthe at theinteractive Python promptinterpreter. This is great for mathlearning and experimenting, shortbut bitsyou ofcan't code,easily andsave testingor edit your work. For longerbigger ideasprojects, itwe'sll easierwrite toour store thePython code in a file. Let's get some practice with this!
 
<ol>
<li>Download the file http://mit.edu/jesstess/www/BostonPythonWorkshop7BostonPythonWorkshop8/nobel.py by right-clicking on it and saying to save it as a ".py" file to your Desktop. The ".py" extension hints that this is a Python script.</li>
<li>Open a commandterminal 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 homeDesktop directory. See [[Boston Python Workshop 8/Friday#Goal_.234:_practice_navigating_the_computer_from_a_command_prompt_practice_navigating_the_computer_from_a_terminal|navigating from a command promptterminal]] for a refresher on those commands.</li>
<li>Once you are in your homeDesktop directory, execute the contents of <code>nobel.py</code> by typing
 
<pre>
Line 375 ⟶ 402:
</pre>
 
at athe commandterminal prompt.
 
<code>nobel.py</code> introduces two new concepts: comments and multiline strings.</li>
Line 389 ⟶ 416:
<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==
 
Please return to the interactive Python interpreter for the rest of the tutorial. And remember: type out the examples. You'll thank yourself tomorrow. :)
 
[[File:Scales.png|100px]]
Line 476 ⟶ 503:
</pre>
 
==FlowMaking Controlchoices==
 
We can use these expressions that <i>evaluate</i> to booleans to make decisions and conditionally execute code.
 
[[File:Fork.png|100px]]
Line 482 ⟶ 511:
====if statements====
 
The simplest way to make a choice in Python is with the <code>if</code> keyword. Here's an example (don't try to type this one, just look at it for now):
We can use these expressions that <i>evaluate</i> to booleans to make decisions and conditionally execute code:
 
&nbsp;&nbsp;&nbsp;&nbsp;<code>if 6 > 5:</code><br />
<pre>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code>
if 6 > 5:
print "Six is greater than five!"
</pre>
 
That wasis our first multi-line piece of code, and the way to entertype it at a Python prompt is a little different. First,Let's break down how to do this (type thethis out step by step):
 
<ol>
<code> if 6 > 5:</code>
<li>First, type the<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>if 6 > 5:</code><br />
<br />
part, and press 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.</li>
 
<li>Press the spacebar 4 times to indent.</li>
part, and press Enter. The next line will have
<li>Type<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>print("Six is greater than five!")</code><br /><br /></li>
<li>Press Enter to end the line. The prompt will still be a <code>...</code></li>
<li>Press Enter one more time to tell Python you are done with this code block. The code block will now execute.</li>
</ol>
 
All together, it will look like this:
<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.
 
Enter 4 spaces, and then type
 
<code> print "Six is greater than five!"</code>
 
Press Enter to end the line, and press Enter again to tell Python you are done with this code block. All together, it will look like this:
 
<pre>
>>> if 6 > 5:
... print ("Six is greater than five!")
...
Six is greater than five!
Line 518 ⟶ 548:
<pre>
if 0 > 2:
print ("Zero is greater than two!")
</pre>
 
<pre>
if "banana" in "bananarama":
print ("I miss the 80s.")
</pre>
 
====more choices: <code>if</code> and <code>else</code>====
 
You can use the <b><code>elseif</code></b> keywordlets toyou execute some code whenonly theif a condition is <code>ifTrue</code>. expressionWhat isn'tif True.you Trywant this:to execute different code if a condition is <code>False</code>?
 
Use the <b><code>else</code></b> keyword, together with <code>if</code>, to execute different code when the <code>if</code> condition isn't <code>True</code>. Try this:
 
<pre>
Line 534 ⟶ 566:
brother_age = 12
if sister_age > brother_age:
print ("sister is older")
else:
print ("brother is older")
</pre>
 
Like with <code>if</code>, the code block under the <code>else</code> statementcondition 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 <b><code>and</code></b> and <b><code>or</code></b> keywords. If two expressions are joined by an <code>and</code>, they <b>both</b> have to be <code>True</code> for the overall expression to be <code>True</code>. If two expressions are joined by an <code>or</code>, as long as <b>at least one</b> is <code>True</code>, the overall expression is <code>True</code>.
 
Try typing these out and see what you get:
Line 568 ⟶ 600:
temperature = 32
if temperature > 60 and temperature < 75:
print ("It's nice and cozy in here!")
else:
print ("Too extreme for me.")
</pre>
 
Line 576 ⟶ 608:
hour = 11
if hour < 7 or hour > 23:
print ("Go away!")
print ("I'm sleeping!")
else:
print ("Welcome to the cheese shop!")
print ("Can I interest you in some choice gouda?")
</pre>
 
Line 587 ⟶ 619:
====even more choices: <code>elif</code>====
 
If you haveneed to execute code conditional based on more than two cases, you can use the <b><code>elif</code></b> 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 <code>True</code> condition or reaches the default <code>else</code> block.
 
<pre>
Line 593 ⟶ 625:
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 <code>True</code>:
 
<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>
 
Anonymous user