Python 2 hour intro: Difference between revisions

no edit summary
imported>Jesstess
(Created page with "This material is intended for a 1.5 - 2 hour interactive lecture. ==Math== 100px Math in Python looks a lot like math you type into a calculator. A...")
 
imported>Jesstess
No edit summary
 
(8 intermediate revisions by the same user not shown)
Line 1:
This material is intended for a 1.5 - 2 hour interactive lecture.
 
[[Python 2 hour intro/Handout| Lecture handout]]
 
==Math==
Line 55 ⟶ 57:
 
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".
 
==Types==
 
[[File:Geometry.png|150px]]
 
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>
type(1)
type(1.0)
</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 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 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.
 
===Command history===
Line 269 ⟶ 250:
 
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.
 
===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"
length = str(len(fish))
print fish + " is a Hawaiian fish whose name is " + length + " characters long."
</pre>
 
===Quotes===
Line 324 ⟶ 293:
print "A" * 40
print "ABC" * 12
h = "Happy"
b = "Birthday"
print (h + b) * 10
</pre>
 
Line 337 ⟶ 303:
1.
<pre>
total = 1.53 - 1/2 + ((-2.0/2) - (1.0/2))5
print total
type(total)
</pre>
 
Line 348 ⟶ 313:
c = "fox jumps over the lazy dog"
print "The " + a * 3 + " " + b * 3 + " " + c
</pre>
 
3.
<pre>
print 2.0 * 123 + str(2.0) * 123
</pre>
 
4.
 
(Remember, copying and pasting is fine here in this practice section -- we'll go back to typing out the code for part 2)
 
<pre>
a = "| (_| -()- -()- -()- -()- | -()- -()- -()- -()- ||\n"
b = "|_\_|_/___|__|__|__|___|__|___|__|___________________________||\n"
c = "|________________________________|__|__()_|__()_|__()__|_____||\n"
d = " ___|)_______________________________________________________\n"
e = "|_/(|,\____/_|___/_|____/_|______|___________________________||\n"
f = "|___/____________________________|___________________________||\n"
g = "| | | () | () | () | | ||\n"
h = "|__\___|.________________________|___\_|___\_|___\_|___|_____||\n"
i = "|__/|_______/|____/|_____/|______|___________________________||\n"
j = "|_____/__________________________|____\|____\|____\|_________||\n"
k = "|____/___________________________|___________________________||\n"
l = "|__/___\_._______________________|__|__|__|__|__|__|___|_____||\n"
 
print d + f + i + e + b + g + a + c + l + h + j + k
</pre>
 
Line 390 ⟶ 329:
<ol>
<li>Download the file http://mit.edu/jesstess/www/BostonPythonWorkshop6/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>Run the script by double-clicking on it. What happens?</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 6/Friday#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 youra text editor (see [[Boston Python Workshop 6/Friday#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>
Line 412 ⟶ 344:
</ol>
 
Let's get back to some interactive examples. Keep typing them out! You'll thank yourself tomorrow. :)
 
==Booleans==
Line 626 ⟶ 558:
<b>Remember that '=' is for assignment and '==' is for comparison.</b>
 
==Lists==
==Writing Functions==
 
* Use lists to store data where order matters.
[[File:Quill.png|100px]]
* Lists are indexed starting with 0.
 
====List initialization====
We talked a bit about functions when we introduced the <code>type()</code> function. Let's review what we know about functions:
 
<pre>
* They do some useful bit of work.
>>> my_list = []
* They let us re-use code without having to type it out each time.
>>> my_list
* 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.
>>> your_list = ["a", "b", "c", 1, 2, 3]
>>> your_list
['a', 'b', 'c', 1, 2, 3]
</pre>
 
====Access and adding elements to a list====
For example:
 
<pre>
length =>>> len("Mississippi"my_list)
0
>>> my_list[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> my_list.append("Alice")
>>> my_list
['Alice']
>>> len(my_list)
1
>>> my_list[0]
'Alice'
>>> my_list.insert(0, "Amy")
>>> my_list
['Amy', 'Alice']
</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>
>>> my_list = ['Amy', 'Alice']
def add(x, y):
>>> 'Amy' in my_list
result = x + y
True
>>> 'Bob' in my_list
False
</pre>
 
====Changing elements in a list====
<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>
>>> your_list = []
def add(x, y):
>>> your_list.append("apples")
result = x + y
>>> your_list[0]
return result
'apples'
>>> your_list[0] = "bananas"
>>> your_list
['bananas']
</pre>
 
====Slicing lists====
or, even shorter:
 
<pre>
>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
def add(x, y):
>>> her_list[0]
return x + y
'a'
>>> her_list[0:3]
['a', 'b', 'c']
>>> her_list[:3]
['a', 'b', 'c']
>>> her_list[-1]
'h'
>>> her_list[5:]
['f', 'g', 'h']
>>> her_list[:]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
</pre>
 
====Strings are a lot like lists====
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>
>>> my_string = "Hello World"
def absoluteValue(number):
>>> my_string[0]
if number < 0:
'H'
return number * -1
>>> my_string[:5]
return number
'Hello'
>>> my_string[6:]
'World'
>>> my_string = my_string[:6] + "Jessica"
>>> my_string
'Hello Jessica'
</pre>
 
* One big way in which strings are different from lists is that lists are mutable (you can change them), and strings are immutable (you can't change them). To "change" a string you have to make a copy:
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>
>>> h = "Hello"
def absoluteValue(number):
>>> h[0] = "J"
if number < 0:
Traceback (most recent call last):
return number * -1
File "<stdin>", line 1, in <module>
else:
TypeError: 'str' object does not support item assignment
return number
>>> h = "J" + h[1:]
>>> h
'Jello'
</pre>
 
==Loops==
<b>Step 4: use the function</b>
 
Use a <code>for</code> loop to do something to every element in a list.
Once you define a function you can use it as many times as you want:
 
<pre>
>>> names = ["Jessica", "Adam", "Liz"]
def add(x, y):
>>> for name in names:
return x + y
... print name
...
Jessica
Adam
Liz</pre>
 
<pre>
result = add(1234, 5678)
>>> names = ["Jessica", "Adam", "Liz"]
print result
>>> for name in names:
result = add(-1.5, .5)
... print result"Hello " + name
...
</pre>
Hello Jessica
 
Hello Adam
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.
Hello Liz</pre>
 
==End of Part 2==
 
Congratulations! You've learned about and practiced writing and executing Python scripts, booleans,making conditionals,choices andwith if/elsebooleans blocksand conditionals, and you'veusing writtenlists your own Pythonand functionsiteration. 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.
 
Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material.
 
 
[[Boston Python Workshop 6/Friday|&laquo; Back to the Friday Workshop page]]
Anonymous user