Olin university chapter/Software/PythonTutorial: Difference between revisions

From OLPC
Jump to navigation Jump to search
Line 34: Line 34:
TurtleWorld.py contains some fun features that allow you to actually use some of your cool programming skills.
TurtleWorld.py contains some fun features that allow you to actually use some of your cool programming skills.


# Run TurtleWorld.py. A GUI (graphical user interface) should pop up, with options like Print Canvas, quit, Make Turtle, Clear, and Run File.
* Run TurtleWorld.py. A GUI (graphical user interface) should pop up, with options like Print Canvas, quit, Make Turtle, Clear, and Run File.
# Hit run file. By default, the file loaded should be turtle_code.py. It should make a nice tree-like picture for you. This is Bob the Turtle's way of welcoming you to his world!
* Hit run file. By default, the file loaded should be turtle_code.py. It should make a nice tree-like picture for you. This is Bob the Turtle's way of welcoming you to his world!
# When you're done with Tree-Bob, click Make Turtle. A table of controls should pop up, including 'bk', 'fd', 'lt', 'rt', 'pu', 'pd', which stand for back, forward, left, right, pen up, and pen down (respectively). Mess with these controls until you get a feel of what they do.
* When you're done with Tree-Bob, click Make Turtle. A table of controls should pop up, including 'bk', 'fd', 'lt', 'rt', 'pu', 'pd', which stand for back, forward, left, right, pen up, and pen down (respectively). Mess with these controls until you get a feel of what they do.
In the rather big text window, there should be code there like
In the rather big text window, there should be code there like
<pre><nowiki>
<pre><nowiki>
world.clear()
world.clear()
bob = Turtle(world)</nowiki></pre>
bob = Turtle(world)</nowiki></pre>
#Open turtle_code.py and see if you can see what codes Allen is using to make the little guy move and stuff. Test your theories in the box and click run code.
* Open turtle_code.py and see if you can see what codes Allen is using to make the little guy move and stuff. Test your theories in the box and click run code.
# When you get comfortable with the coding, open a file and make a script for moving the turtle around. See if you can do something fun, like write your name across the screen in different colors.
* When you get comfortable with the coding, open a file and make a script for moving the turtle around. See if you can do something fun, like write your name across the screen in different colors.



Revision as of 17:33, 25 November 2008

Purpose

Olin OLPC-software team includes a wide variety of people with a variety of skills. This page is created to allow everyone to have fundamentals in programming in python and pygame, in order to create activities for the xo.

This tutorial will only include fundamentals, up to what is taught in Olin's Software Design course. For more complicated cool stuff, please refer to online documentation.

If you want to learn how to design cool things, take Software Design, website found here.

Structure

This tutorial contains five modules, including an extra module for anyone with no exposure to programming in general. Each day includes significantly more advanced material than the day before, so it's up to the reader whether they wish to do all five days at once, or one per week.

The writer also strongly recommends that the suggested projects at the end of each "day" not be skipped, and be done without time constraint, as there's no way you can learn a programming language without searching documentation for every cool function you can think of. (Along that line of thought, Allen Downey's homework assignments are also sweet for extra practice.)


Day 0

This extra module is intended for anyone who does not have much exposure to object oriented programming (ie Java, Python, C++). For those who just want to learn Python, you can skip this module.

In this module, we will experiment with using other people's code to draw pretty pictures and get comfortable with dot notation.

Swampy

(Swampy is created by Allen Downey, and is used here with his permission)

Go to the Swampy install page and download Swampy.zip. This is Allen Downey's sweet collection of various fun programs. Put the zip file in your folder of choice, and open them in your editor of choice. (IDLE comes with our laptops, in which you hit F5 to run.)

Try running some of the programs suggested on the install page. Take some time to poke around the code you're curious how things work.

(Not all the programs will run in Windows, so if you are super curious, reboot into Linux and mess around with it there.)

TurtleWorld.py

TurtleWorld.py contains some fun features that allow you to actually use some of your cool programming skills.

  • Run TurtleWorld.py. A GUI (graphical user interface) should pop up, with options like Print Canvas, quit, Make Turtle, Clear, and Run File.
  • Hit run file. By default, the file loaded should be turtle_code.py. It should make a nice tree-like picture for you. This is Bob the Turtle's way of welcoming you to his world!
  • When you're done with Tree-Bob, click Make Turtle. A table of controls should pop up, including 'bk', 'fd', 'lt', 'rt', 'pu', 'pd', which stand for back, forward, left, right, pen up, and pen down (respectively). Mess with these controls until you get a feel of what they do.

In the rather big text window, there should be code there like

world.clear() 
bob = Turtle(world)
  • Open turtle_code.py and see if you can see what codes Allen is using to make the little guy move and stuff. Test your theories in the box and click run code.
  • When you get comfortable with the coding, open a file and make a script for moving the turtle around. See if you can do something fun, like write your name across the screen in different colors.


Yay! you have just completed the first major software Design homework!

Suggested project

Create 4 functions that automate the process of writing the letters "H","E","L",and "O". Then write an all-encompassing function that writes "Hello" across the screen.

Day 1

Characteristics of Python:

Unlike many more popular languages like Java and C, Python is an interpreted language, as opposed to compiled. In a compiled language, your code is first optimized and translated into an intermediate language before it is translated into machine code and run. In an interpreted language, the code is translated into byte code on the fly. 

What does this mean for you as a programmer? Most significantly, it allows you to test your code in the command line. For those familiar with Matlab or Scheme, you might be thinking "So what?" Well, you live in a very ideal world. For those who program in C or Java, your code is more structured into blocks, in which only the main block is executed. If you have a structure like

public void main(){ printHello() } public void printHello(){ System.out.println("Hello World!"); }


That should work fine in Java. Before code gets run, it gets rearranged and optimized so that everything works out great. However, if you tried the equivalent in Python

def main() printHello() def printHello() print "Hello World!"

Because python interprets code in order, this will not work. Without knowing what printHello() is, main() cannot run.

Instead, we need something more like

def printHello() print "Hello World!" def main() printHello()

In any case, let's fire up a command window and try out some code.

In Windows, you can go to Start >> run, type 'cmd'. When the black box appears, type 'python'. Your left-hand-thingy should change from C:> to >>>. To exit, press Ctrl+Z.

Idle also comes with command line interface. You can open any file in Idle and press F5 - just running a program should pull up the command window.

In Linux, just open the terminal and hit 'python'. Again, you will get >>>, and press Ctrl+D to exit.

Let's start with the basics. Try some basic arithmetic.

>>> 4+2 6 >>> 2*5 10 >>> 24253+25^234 24124 >>>

Ok. Just like Matlab so far. Let's try something else.

>>> 25/10 2

Hmm, that doesn't seem right, last time I checked. I wonder what could be wrong??? Some of you may recognize this as classic floating point division mistake. What's happening here is that python has stored the values 25 and 10 as integers, and when it divides them, it can only return another integer. In this case, it rounds the answer for you. In order to use floating point division for real, you have to actually use a decimal point.

>>> 25./10 2.5 >>> 25/10. 2.5

As soon as that decimal point is there, the float (or I believe in this case, a double, which is just a float with twice as many digits) is declared, and you can continue work as usual.

But this brings up a fundamental difference between Matlab, a nice simulation environment, and Python, a programming language. Matlab is slow and clunky because it does many things for you, like convert integers to floats when necessary. Python is fast, and flexible, but requires you to kind of know what you're doing.

Let's try something Matlab is not so good at dealing with: strings. Try some of the following stuff:

>>> "Blubbermonkeys" 'Blubbermonkeys' >>> "I love OLPC!" 'I love OLPC!'

Ok, yeah, boring. Let's do some string concatenation

>>> 'Tank' + 'Nikki' 'TankNikki'

What about escape characters? Well, the usual apply. Use '\n' for newline, '\t' for tab, and you can look up the rest.

>>> 'Tank\n Nikki\n Mel\n SJ' 'Tank\n Nikki\n Mel\n SJ'

Ewww... Ok, so just like in MatLab, where you can technically display stuff by not putting in that last semicolon, it isn't the most elegant way of doing it. In MatLab, we use 'disp' to display things intentionally. In Python, we use 'print'.

>>> print 'Tank\n Nikki\n Mel\n SJ' Tank

Nikki
Mel
SJ

Sweet! That looks better. Hey, let's define a variable! For you MatLab lovers out there, it's just like Matlab. For you Java and C fans out there, you will love Python, because it's much easier. You don't need to explicitly state the type of variable before declaring it; Python just kind of knows. Well, sort of. Let's look just at integers and strings.

>>> a = 3 >>> b = 4 >>> c = a**2 + b**2 >>> print c 25

(Note that exponents are not ^, but **.)

>>> name = 'Yifan' >>> print name + ' is Great!' Yifan is Great!

Datatypes:

At this point it is most prudent to look at some datatypes. As I have hinted to already, Python has floats, doubles, integers, and strings. The other major datatypes are tuples, lists, and dictionaries.

Lists, as its name represents, is just a collection of stuff in order, and are usually represented in brackts. There are many kinds of lists, such as:

>>> l = [1,2,3,4,5] >>> print l [1, 2, 3, 4, 5] >>> l = ['Elsa','Colin','Xy'] >>> print l ['Elsa', 'Colin', 'Xy'] >>> for i in l: print i + ' is AWESOME!' Elsa is AWESOME! Colin is AWESOME! Xy is AWESOME!

Hey look at that! Lists allow you to use for loops! If it isn't evident yet, the for loop structure is done by iterating through a list. Actually, this is exactly what you do when you use a for loop in matlab; when you say

for x = 1:10

<do stuff>

What you actually are doing is instantiating a vector x including the integer values 1-10, and looping through each element in x.

In Python, it's exactly the same, except the syntax is more like

for x in [1,2,3,4,5,6,7,8,9,10]: <do stuff>

(note the colon)

Or, for shorthand,

for x in range(10): <do stuff>

(Note to audience. Actually I am lying to you. range(10) returns a list of [0,1,2,3,4,5,6,7,8,9], not [1,2,3,4,5,6,7,8,9,10]. In the real world, everything starts with 0; in Matlab, they start with 1. How odd.)

Tuples

Tuples are very much like lists, except they aren't modifiable. They are instantiated using '()' ie:

>>> x = (1,2,3) >>> x[1] = 3 Traceback (most recent call last):

 File "<pyshell#36>", line 1, in <module>
   x[1] = 3

TypeError: 'tuple' object does not support item assignment

Tuples are useful for things that you want one way forever, like the size of your window in a GUI. If you ever need to convert a tuple to a list, you can just use 'list()' as follows:

>>> a = (3,1,4) >>> list(a) [3, 1, 4]

Dictionaries are kind of sort of like lists, except that they are unordered, and like actual dictionaries, come in a key-value pair. That is to say they are mostly used for lookup. You indicate dictionaries using 'dict([<key>,<value>],[<key>,<value>])' or using curly brackets '{}'

dict([('Brian', 'Mod Con'), ('Mark', 'ICB'), ('Ben', 'Design Nature')])


>>> dict([('Brian', 'Mod Con'), ('Mark', 'ICB'), ('Ben', 'Design Nature')]) {'Brian': 'Mod Con', 'Ben': 'Design Nature', 'Mark': 'ICB'}

Note how the order is not preserved. To iterate through a dictionary, you can use d.keys() to go through the keys, and d.values() to go through the values. To go through both, you can use d.items() to get a tuple pair.

Examples: >>> d = dict([('Brian', 'Mod Con'), ('Mark', 'ICB'), ('Ben', 'Design Nature')]) >>> for i in d.keys(): print 'I love ' + i

gives I love Brian I love Ben I love Mark >>> for i in d.values(): print 'I love ' + i

gives: I love Mod Con I love Design Nature I love ICB

>>> for k,v in d.items(): print 'I love ' + k + ' and ' + v

I love Brian and Mod Con I love Ben and Design Nature I love Mark and ICB

Sweet. That's all I had for day 1.

Summary project: Organizing list of senators

In the spirit of the election, I have copy-pasted a list of US senators into listOfCongress.txt. If you open it you can see that I made no efforts whatsoever to make it neat - the original site organized it by alphabet, in two columns seperated by a tab. At the end of each letter, there's an annoying '^ return to top' text.

Your job is to reorganize this text into something much nicer to read, preferably a single column without letter headings and ^return to top interjections.



Day 2
- classes, objects, functions
- cards

Day 3
- files
- Markov Analysis

Day 4
- GUI

Day 5
- Pygame
 
interesting topics:
files
gui
networking?
threads?
remote projects?