Olin university chapter/Software/PythonTutorial: Difference between revisions
(New page: adfasdfsdf) |
No edit summary |
||
Line 1: | Line 1: | ||
Plan for cram python teaching week |
|||
adfasdfsdf |
|||
purpose: to help people who have or haven't learned programming learn Python. Should include basics, fundamentals, nothing too interesting. Documentation exists for interesting stuff |
|||
If you want to learn how to design cool things, take Software Design. |
|||
Also, if you intend on programming for something non-gamy, take software design or look at Allen's website - a trove of good stuff! |
|||
http://allendowney.com/sd08spr/hw12/hw12.html |
|||
(Allen's stuff is taken with his permission) |
|||
5 modules, 1 each day |
|||
at the end of the week, we have a jam. |
|||
We might be able to sustain this for a while... |
|||
Day 0 (for people who want basic intuition on Object Oriented Programming) |
|||
The Swampy Suite |
|||
- Go to http://allendowney.com/swampy/install.html and download Swampy. This is Allen Downey's sweet collection of various fun programs. Try some o f the ones suggested on the webpage, and poke around at the code if you're curious how things work. |
|||
If you intend on running these programs on Windows, you can open the files in IDLE and press F5 to run it. I don't think all the programs work well with IDLE, but TurtleWorld.py should. |
|||
TurtleWorld.py |
|||
I personally find TurtleWorld.py to be the most educational program (probably because it's what we used in Software Design.) Here are some things you can try |
|||
1) Run TurtleWorld.py. A gui should pop up, with options like Print Canvas, quit, Make Turtle, Clear, and Run File. |
|||
2) 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! |
|||
3) When you're done with Tree-Bob, click Make Turtle. A table of controls should pop up, bk, fd, lt, rt, pu, pd, which stand for back, forward, left, right, pen up, and pen down. Mess with these controls until you get a feel of what they do. |
|||
4) In the rather big text window, there should be code there like world.clear() and 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. |
|||
5) 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! |
|||
Day 1 (for people who can program fairly well and just want to learn python, start here) |
|||
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? |
Revision as of 17:04, 25 November 2008
Plan for cram python teaching week
purpose: to help people who have or haven't learned programming learn Python. Should include basics, fundamentals, nothing too interesting. Documentation exists for interesting stuff If you want to learn how to design cool things, take Software Design.
Also, if you intend on programming for something non-gamy, take software design or look at Allen's website - a trove of good stuff!
http://allendowney.com/sd08spr/hw12/hw12.html
(Allen's stuff is taken with his permission)
5 modules, 1 each day
at the end of the week, we have a jam.
We might be able to sustain this for a while...
Day 0 (for people who want basic intuition on Object Oriented Programming) The Swampy Suite
- Go to http://allendowney.com/swampy/install.html and download Swampy. This is Allen Downey's sweet collection of various fun programs. Try some o f the ones suggested on the webpage, and poke around at the code if you're curious how things work. If you intend on running these programs on Windows, you can open the files in IDLE and press F5 to run it. I don't think all the programs work well with IDLE, but TurtleWorld.py should. TurtleWorld.py I personally find TurtleWorld.py to be the most educational program (probably because it's what we used in Software Design.) Here are some things you can try 1) Run TurtleWorld.py. A gui should pop up, with options like Print Canvas, quit, Make Turtle, Clear, and Run File. 2) 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! 3) When you're done with Tree-Bob, click Make Turtle. A table of controls should pop up, bk, fd, lt, rt, pu, pd, which stand for back, forward, left, right, pen up, and pen down. Mess with these controls until you get a feel of what they do. 4) In the rather big text window, there should be code there like world.clear() and 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. 5) 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!
Day 1 (for people who can program fairly well and just want to learn python, start here)
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?