Boston Python workshop 2/Friday tutorial: Difference between revisions

imported>Jesstess
No edit summary
 
(30 intermediate revisions by 8 users not shown)
Line 1:
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.
 
==Math==
 
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 56:
==Types==
 
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:
 
<pre>
Line 71:
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 produceproduces 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. 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==
Line 89:
</pre>
 
Giving a name to something, so that you can refer to it by that name, is called '<b>assignment'</b>. Above, we assigned the name 'x' to 4, and after that we can use <code>x</code> wherever we want to use the number 4.
 
Variables can't have spaces or other special characters, and they need to start with a letter. Here are some valid variable names:
Line 154:
</pre>
 
are both valid Python '<b>syntax'</b>.
 
<pre>
Line 170:
==Strings==
 
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>
Line 218:
<code>TypeError: cannot concatenate 'str' and 'int' objects</code>
 
Python is giving us a '<b>traceback'</b>. A traceback is details on what was happening when Python encountered an Exception or Error -- something it doesn't know how to handle.
 
There are many kinds of Python errors, with descriptive names to help us humans understand what went wrong. In this case we are getting a '<code>TypeError'</code>: we tried to do some operation on a data type that isn't supported for that data type.
 
Python gives us a helpful error message as part of the TypeError:
Line 240:
</pre>
 
produces a <code>TypeError</code>. We are telling Python to concatenate a string and an integer, and that's not something Python understands how to do.
 
In the similar expression
Line 287:
</pre>
 
or we can '<b>escape'</b> the quote with a backslash:
 
<pre>
Line 304:
</pre>
 
==PythonPart scripts1 Practice==
 
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.
 
Open your text editor and create a new file called test.py. The .py extension helps us and other programs recognize that this file will contain Python code.
 
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.
Copy the following lines into your file:
 
<nobel.py>
 
Save the file.
 
Execute the contents of the file by typing at a terminal prompt:
 
python nobel.py.
 
this file introduces two new concepts: comments and multiline strings. Read
through the file careful and check your understanding of both the comments and
the code.
 
Practice
 
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.
 
1.
<pre>
total = 1.5 - 1/2 + ((-2.0/2) - (1.0/2))
print total
type(total)
</pre>
 
2.
<pre>
a = "quick"
b = "brown"
c = "fox jumps over the lazy dog"
print "The", a * 3, b * 3, c
</pre>
 
3.
<pre>
print 2.0 * 123, "2.0" * 123
print 2.0 * 123 + str(2.0) * 123
</pre>
 
4.
<pre>
a = "| (_| -()- -()- -()- -()- | -()- -()- -()- -()- ||\n"
b = "|_\_|_/___|__|__|__|___|__|___|__|___________________________||\n"
c = "|________________________________|__|__()_|__()_|__()__|_____||\n"
d = " ___|)_______________________________________________________\n"
d = "___|)________________________________________________________\n"
e = "|_/(|,\____/_|___/_|____/_|______|___________________________||\n"
f = "|___/____________________________|___________________________||\n"
Line 360 ⟶ 345:
 
print d + f + i + e + b + g + a + c + l + h + j + k
</pre>
 
==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==
 
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/BostonPythonWorkshop2/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_2/Friday_setup#Goal_.234:_practice_navigating_the_computer_from_a_command_prompt|navigating from a command prompt]] for a refresher on those commands.</li>
<li>Once you are in your home directory, execute the contents of <code>nobel.py</code> by typing
 
<pre>
python nobel.py
</pre>
 
at a command prompt.
 
<code>nobel.py</code> introduces two new concepts: comments and multiline strings.</li>
 
<li>Open <code>nobel.py</code> in your text editor (see [[Boston_Python_workshop_2/Friday_setup#Goal_.232:_Prepare_a_text_editor|preparing your text editor]] for a refresher on starting the editor).</li>
<li>Read through the file in your text editor carefully and check your understanding of both the comments and the code.</li>
</ol>
 
==Booleans==
 
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>
True
</pre>
 
<pre>
type(True)
</pre>
 
<pre>
False
</pre>
 
<pre>
type(False)
</pre>
 
You can test if Python objects are equal or unequal:
 
<pre>
0 == 0
</pre>
 
<pre>
0 == 1
</pre>
 
Use <code>==</code> to test for equality. Recall that <code>=</code> is used for <i>assignment</i> (e.g. <code>my_string == "Hello"</code>).
 
This is an important idea and can be a source of bugs until you get used to it: <b>= is assignment, == is comparison</b>.
 
Use <code>!=</code> to test for inequality:
 
<pre>
"a" != "a"
</pre>
 
<pre>
"a" != "A"
</pre>
 
<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class:
 
<pre>
1 > 0
</pre>
 
<pre>
2 >= 3
</pre>
 
<pre>
-1 < 0
</pre>
 
<pre>
.5 <= 1
</pre>
 
You can check for containment with the <code>in</code> keyword:
 
<pre>
"H" in "Hello"
</pre>
 
<pre>
"X" in "Hello"
</pre>
 
Or check for a lack of containment with <code>not in</code>:
 
<pre>
"a" not in "abcde"
</pre>
 
<pre>
"Elvis" not in "Elvis has left the building"
</pre>
 
==Flow Control==
 
We can use these expressions that <i>evaluate</i> to booleans to make decisions and conditionally execute code:
 
<pre>
if True:
print "I'm True!"
</pre>
 
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>
>>> if True:
... print "I'm True!"
...
"I'm True!"
</pre>
 
So what is going on here? When Python encounters the <code>if</code> keyword, it <i>evaluates</i> the <i>expression</i> following the keyword and before the colon. If that expression is <b>True</b>, Python executes the code in the indented code block under the <code>if</code> line. If that expression is <b>False</b>, Python skips over the code block.
 
In this case, because <code>1</code> is truthy, Python executes the code block under the if statement, and we see "I'm True!" printed to the screen. What do you think will happen with this one:
 
<pre>
if False:
print "I'm True!"
</pre>
 
<pre>
if 1:
print "1 is truthy"
</pre>
 
<pre>
if 0:
print "0 is truthy"
</pre>
 
<pre>
if "test":
print "non-empty strings are truthy"
</pre>
 
<pre>
if "":
print "empty strings are truthy"
</pre>
 
You can use the <code>else</code> keyword to conditionally execute code when the expression for the <code>if</code> block isn't true:
 
<pre>
sister_age = 15
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> statement must be indented.
 
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.
 
<pre>
1 > 0 and 1 < 2
</pre>
 
<pre>
1 < 2 and "x" in "abc"
</pre>
 
<pre>
"a" in "hello" or "e" in hello"
</pre>
 
<pre>
1 <= 0 or "a" not in "abc"
</pre>
 
<pre>
temperature = 32
if temperature > 60 and temperature < 75:
print "It's nice and cozy in here!"
else:
print "Too extreme for me."
</pre>
 
<pre>
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>
 
 
[[Boston Python workshop 2/Friday setup|&laquo; Back to the Friday setup page]]
Anonymous user