Python 2 hour intro: Difference between revisions

no edit summary
imported>Jesstess
No edit summary
imported>Jesstess
No edit summary
 
(7 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 327 ⟶ 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 349 ⟶ 344:
</ol>
 
Let's get back to some interactive examples. Keep typing them out! You'll thank yourself tomorrow. :)
 
==Booleans==
Line 563 ⟶ 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