Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

What programming language should I use/learn?

I get asked often, "Which programming language should I start with?" or "I teach _______ which language would be the best for my classroom?" My goal is not to promote one language but show you the benefits of each of the more popular choices out there and let you make your own decision. There really is no one "best" language, just the best language for what you are interested in doing.

As always I promote technology that:

  1. Enhances or encourages learning. Programming is one great way to implement Computational Thinking into your class.
  2. The software is free and open source.

Disclaimer: These are intended to be a summary. They are presented in no particular order.

Python

Free? FOSS (Free as in zero cost and open source)
Requires an installation? Yes but there are web based options like sage math notebook. Python comes preinstalled on Mac and Linux.
Strengths: 
  • The syntax is very high level so you and your students can take your ideas and very quickly turn them into code. 
  • Python is interpreted so as soon as you press enter or run the code you can see the results. 
  • It has a large number of modules and support for graphics (e.g. VPython), physics, math, language parsing and more.
  • Great for prototyping, web, data mining/processing, and almost anything!
Recommended Tutorials:
    Codingbat


Javascript

Free? FOSS
Requires an installation? No
Strengths:
  • Coupled with HTML5 and CSS allows you to add a lot of power and interactivity to your web pages and applications.
  • Gives you to access web APIs (directory of available APIs) and use other services.
FYI: Javascript fails silently (meaning if there is a bug, it just won't work the way you intended, there won't be an error message) so use lots of debugging techniques and logs to debug. This is far easier than it may sound and is useful to learn regardless of what language you are using.
Recommended Tutorial:


Processing

Free? FOSS
Requires an installation? Yes
Strengths:
  • Designed to be very easy to make something visual, beautiful and/or interactive.
  • With both Processing and Arduino, it provides an introduction to C++ that is less intimidating.
Recommended Tutorials:
    Examples in the Processing software (Select File and then Examples)


Arduino

Free? 
  • Hardware: No but Open Source (Sparkfun, Adafruit, and Radio Shack are trusted suppliers)
  • Software:  FOSS
Requires an installation? Yes
Strengths:
  • Works with off the shelf parts (e.g. motors, LEDs) to cheaply and easily build projects that sense, move, light up, etc.
  • Many "shields" are available to easily add functionality like Bluetooth, Wifi, audio, etc.
  • Hardware is relatively inexpensive (~$20-30)
  • Interfaces easily with Processing to add interactivity and data visualization.
Recommended Tutorials:
    Examples in the Arduino software (Select File and then Examples)
    Sparkfun Education

Subscribe and follow Phil for more on education and technology.

Updated Python: How to Think Like a Computer Scientist

I hold a special place in my heart for the How to Think Like a Computer Scientist tutorial. When my former teacher and then colleague Michel Paul told me about this great language Python I went home and checked out a few tutorials.

Jeff Elkner's How to Think... was not only the easiest introduction to the syntax of the language, I still use it as one of my references as well as for my students. The tutorial started out as a series of explanations and tutorials but recently has evolved into a much more interactive experience. For many students it is difficult to get software installed on their home computers and sadly it can be difficult for teachers to have it on their school network. Brad Miller has released an updated version of How to Think Like a Computer Scientist with interpreters built into the lesson so students can learn right from the browser.


The ability to program from within the browser is making a huge impact on one's ability to learn right away. Some great examples of this beyond How to Think... are: W3 School (HTML, CSS, Javascript, etc), SAGE (Math), and CodeAcademy (lots of great potential here).

You will need a Google account (free) and an up to date browser (Chrome, Firefox, IE). In addition to the interactivity, video tutorials and an administrative back end is being tested and will be opened up at the end of the semester for use with your students. Brad Miller, continues to refine this project and is committed to making it useful and open to as many as possible. New tutorials have been added to take you from Hello World to full blown Object Oriented Programming (trust me it's awesome).

I can personally testify to the quality of these lessons. If you are motivated you could go through these in a weekend or so and be off and running to the great possibilities in using programming with your students. As I have said before, it will provide opportunities for students to try ideas they never could have before. I think of all my students and I have been able to accomplish with Python and it all started with the How to Think Like a Computer Scientist tutorial. I can only imagine what could happen if every teacher who read this blog gave it a shot and passed it on to their students.

Subscribe and Connect to BrokenAirplane and stay up to date with the best resources for your classroom.

I'm Not Texting I'm Programming!

Update: This app is available now as Physics Gizmo on Google Play.

No less than a century ago, it was possible to learn everything we knew about science. The only requirements were an ability to read, an extensive library, and perhaps the equipment to carry out your own experiments. Now we have entered a new era of science where literacy is more widespread and between the Internet and Libraries we have every resource imaginable at our fingertips.

Two big problems remain, science has diversified and grown so much that it is difficult for scientists to know everything about their own field let alone another. The other issue is how science equipment remains financially out of reach of amateurs and explorers. The major scientific research is driven by that which will have a financial return and so science for its own sake is limited. This is even more evident in schools who are cutting science to save the rest of their budgets and focus on less expensive (and more tested) subjects This must change if a steady stream of innovation is to continue.

The hacker spirit is a deeply embedded part of science. Now out of necessity and pure enjoyment, many are directing their attention away from software development but to hardware. In the August issue of Wired, the BioHacker movement features those who wish to reduce the cost of doing Genetic analysis.

Do you know where these DIY Biologists expect to see the most impact? Schools! For students to do science instead of just reading about it. Arduinos, Makerbots, Robotics, and more are forever changing the opportunities students have to create.

At my school we spent a lot of time in labs and projects. What was lacking was quality data. Unfortunately the tools and sensors available to students are expensive and limited. So I did what I always do, I sat down and wrote some code :)

I love my Android phone and each day I hear about the insane number of new activations everyday. The smart phone is getting smarter and cheaper just as technology always does. Just as we saw an explosion of Desktops and later Laptops in the 1990-2000s, we are seeing an even speedier rate of adoption of smart phones. While looking at my phone one day, I realized how many sensors/tools it has built in seamlessly to its interface (Internet, Accelerometer (motion sensor), Gyroscope, Light, Sound) which if purchased separately would be thousands of dollars and would not play well with each other.

So I wrote a program which logs motion and then uploads it to your Google Docs account. You can see some screenshots below of the results.

Jumping up and down

Dropping my phone (onto a pillow)

To do this, I used sl4a (Scripting Language for Android). With this you can code in Python, Ruby, Javascript (and more) and do almost anything with your Android phone. It has a built in editor so you can quickly type code into the phone (hence this post's name) or you can code it in your favorite editor and then transfer it to the SD card on your phone.

Why did I use sl4a instead of making a nice pretty app using Android's SDK? This application uses the Google Doc APIs (basically commands to communicate between an app and and a program like Twitter or Facebook) and Python. If you look at the code it could be done by any of our students with a free weekend. It may look a little complicated at first but there are just a lot of function calls to save code. Just like most other Python code, it reads like a story (login, get the parameters, sense, upload).

I believe sl4a could take students who may or may not have used App Inventor or Scratch to the next level and open up a world of possibilities to them. sl4a has been used to send collect data on a phone being launched into space and many other exciting projects involving Twitter, Robots, Arduino and more!


I wanted to use sl4a so everyone who knows Python could see the code and hopefully improve on it. I don't have the time right now, but I would love to see other sensors added, the ability to review and display the data/graph on the phone, interface with Arduino, and store data on the phone if it logs data longer than 1 minute, and perhaps even add a pretty GUI. I'm hoping that by open sourcing this, others will want to jump on board and help out. Cellbots have set the bar really high and have their own incredible data logging app and if they integrated Google Docs uploading I would say their app is perfection.

My hope is as more educators/students realize their ability to create, scientific tools will become available to all. People like Steve Dickie, the Arduino team, Geogebra, and many others are working really hard to ensure that the cost to do STEM is reduced dramatically.

You could walk into your class on Monday and ask your students how many of them have an Android phone, you may be surprised that there are enough for one per group. Think of all of the experiments you could do with nothing else but your phone. I can't wait for this year's Magic Mountain Physics Day and see how many students could get data from a roller coaster and directly upload it to their Google Docs (and check it while still at the park from the GDocs Android app).

Look how easy it is to make a little popup on your screen!
import android
droid=android.Android()
droid.makeToast("Hello Android")


If you want to give this a shot, go to the sl4a website and download the apk (the installer). Your other options are to click this link, or scan the barcode on the right with your Android phone. Follow the User Guide to get Python (or the other languages) installed on your phone.

Now, you are ready to start coding on/for your phone. There are some great tutorials on the sl4a website, I also recommend the book Pro Android Python with SL4A. In my code below I list a few other resources that were helpful to the doScience project.

If your code is relatively small you can share it via barcode but this app falls just above that threshold. So you can copy and paste it from below (just please respect the Creative Commons licence) into your Python Editor or download the doScience file directly. Save it to your SD card in the sl4a/scripts folder. This code must be run on a phone or a computer connected to a phone running an sl4a server (much simpler than it sounds).

Note: It will ask you to login to your Google account. As you can see from the code below, no one is able to access that information since it is kept hidden from even the developer by the dialogGetPassword method in line 41.

I hope this app inspires you to do something great. If you know how to program, build, create will you please lend your talents to this projects or the many others out there. If you don't know how to create, then learn as it is the most incredible thing to be a Maker and you will inspire others. Before you know it, the revolution will be underway (oh wait it already is, come join us)!

Subscribe and Connect to BrokenAirplane and stay up to date with the best resources for your classroom.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
'''This code is licenced under a Creative Commons
Attribution-NonCommercial-ShareAlike 3.0 Unported Licence.
Created by Phil Wagner 2011 www.brokenairplane.com. This code allows data logging and uploading to Google Spreadsheets.
It exists so students can to do Science when 
the cost of Science Equipment is too expensive. Additional features can be added
but this paragraph should always remain in the code.'''

#Future features - Additional Sensors, Review, Display Data/Graph on Phone
#interface with Arduino/ADK

#Helpful Resources:
#http://code.google.com/p/android-scripting/ (sl4a)
#http://code.google.com/ (Google APIs and resources)
#http://www.adaptcode.com/using-google-spreadsheets-as-a-database-in-the-cloud/
#http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.spreadsheet.text_db.html

import android
import time
import gdata.spreadsheet.service
import gdata.spreadsheet.text_db
import string

droid = android.Android()

dt=100 #Time between sensing

def countdown():
    #3 Second Countdown and Vibrate
    droid.vibrate(100)
    time.sleep(1)
    droid.vibrate(100)
    time.sleep(1)
    droid.vibrate(100)#3 second countdown
    time.sleep(1)
    droid.vibrate(300)
    return

def login(myEmail='example@gmail.com', password=''):    #Get Email and Password and login
    while password == '':
        email = droid.dialogGetInput("Email", "Enter the email account where the Data will be uploaded to:",myEmail).result
        password=droid.dialogGetPassword("Password", "Enter the account password where the Data will be uploaded to:").result
        try:
            client = gdata.spreadsheet.text_db.DatabaseClient()
            client.SetCredentials(username=email, password=password)
        except gdata.spreadsheet.text_db.BadCredentials:
            droid.dialogCreateAlert("Username or password incorrect.")
            droid.dialogSetPositiveButtonText("OK")
            droid.dialogShow()
            redo = droid.dialogGetResponse()
            password =''
            continue
        else:
            return client

def spreadSheetSetup(client, defaultTitle = 'Science Data'):
    versionNumber = client.GetDatabases(name=defaultTitle)
    if len(versionNumber) > 0:
        droid.dialogCreateAlert('Science Data %d' % len(versionNumber))
        droid.dialogSetPositiveButtonText("OK") #Yes option box
        droid.dialogShow()
        understood = droid.dialogGetResponse()
        spreadsheetTitle = defaultTitle+' '+str(len(versionNumber))
    else:
        spreadsheetTitle = defaultTitle
    return client.CreateDatabase(spreadsheetTitle)

def time2Sense(defaultTime=5000):
    maxTime =0
    #Enter time for sensing
    while maxTime == 0: ##How long to sense?
        try:
            maxTime=int(droid.dialogGetInput("Time", "How long to collect data (in milliseconds):",str(defaultTime)).result)
        except TypeError:
            droid.dialogCreateAlert("Please enter a numeric time")
            droid.dialogSetPositiveButtonText("OK")
            droid.dialogShow()
            droid.dialogGetResponse()
            continue
        if maxTime > 30000: #30 seconds max for optimal upload
            droid.dialogCreateAlert("Warning this could take a long time to upload.")
            droid.dialogSetPositiveButtonText("I accept the risks")
            droid.dialogSetNegativeButtonText('New time')
            droid.dialogShow()
            check = droid.dialogGetResponse().result
            if check['which'] == 'positive':
                return maxTime
            else:
                maxTime = 0
                continue
        return maxTime

def doScience():
    droid.dialogCreateAlert('Are you ready', 'Click yes to begin sensing, or no to cancel')
    droid.dialogSetPositiveButtonText("Let's do science!") #Yes option box
    droid.dialogSetNegativeButtonText("Nah let's cancel") #No option box
    droid.dialogShow()
    return droid.dialogGetResponse().result

def senseAccel(endTime,dt=100):    #Sense and store accel data
    timeSensed=0
    tempScience = []
    droid.startSensingTimed(2,dt) #dt = time between sensings
    while timeSensed <= endTime:
        tempScience.append(droid.sensorsReadAccelerometer().result) #add new accel data to list
        time.sleep(dt/1000.0)
        timeSensed+=dt
    #Stop Sensing
    droid.makeToast("Done")
    droid.vibrate(300)
    droid.stopSensing()
    return tempScience

def main():
    db =spreadSheetSetup(login())
    endTime = time2Sense()
    ready = doScience()
    if ready['which'] == 'positive':
        countdown()
        science = senseAccel(endTime,dt)
        table=db.CreateTable('Accelerometer',['t','x','y','z']) #Beware spreadsheet column names cannot be uppercase if you are going to add to them later http://code.google.com/p/gdata-python-client/issues/detail?id=363
        droid.dialogCreateHorizontalProgress('Progress','Uploading to Docs',len(science)*3 )
        droid.dialogShow()
        progress = 0
        time = 0
        for data in science:
            table.AddRecord({'t':str(time),'x':str(data[0]),'y':str(data[1]),'z':str(data[2])}) #AddRecord requires strings as arguements str()
            progress+=3
            time+=dt
            droid.dialogSetCurrentProgress(progress)
        droid.dialogCreateAlert('Done', 'Go check your data on Docs')
        droid.dialogSetPositiveButtonText("OK") #Yes option box
        droid.dialogShow()
        droid.dialogGetResponse()

if __name__ == "__main__":
        main()

What Does Our Music Say About Us? Python Music Experiment Part 2

Subscribe to BrokenAirplane!

Perhaps you tried my class' experiment with their favorite music, finding out the frequency of a word and seeing if there was any significance in the repetition of that word. We did a another experiment where we analyzed the Billboard Top 100 for 2000-2009.

The words that came up most frequently (with a couple of random outliers) were:
Me
My
Got
We
I’m
Love
Your
Mine
With
Baby
I
You
Like
Do you see a connection? They did. Especially as they are reading Romeo and Juliet in their Humanities class. Love and possessions is what the students felt was being repeated over and over. While the profitability in increasing desire and hype over possessions is obvious, I posed to them, "Why might a lyricist or company hype up songs about love?" One student's response, "Because when you are in love you will do anything for them or buy them anything."

I then posed to them the challenge of writing a song (a good song!) that does not use any of these words. It was like lyrical Taboo. It would be interesting to see what our culture would be like if we didn't use these songs in all of our most played songs.

Subscribe to BrokenAirplane and keep up with all of the latest education and technology resources!

What Does Your Music Say About You? Python Music Experiment Part 1

Subscribe to BrokenAirplane

I love the last project of the year. I have spent an entire year with these students learning about their interests and  helping them become proficient in math, science, and programming. I like to experiement with the last project and try something new that hopefully will go well but at least can be refined for next year. I was pleasantly surprised about how this final project went and so I thought I would share it with you.

I am always on the lookout for inspiration for projects and this one began 3 years ago with a fascinating article about Pandora (sorry I don't have it anymore). I was so interested in the way the system learned what you like and don't based upon more than just genre. In fact it was based upon over 400 different factors according to the Music Genome Project on which Pandora is based. I thought this year I would have the students analyze music based upon one of those factors, lyrics.

I asked the students to find 20 song lyrics and paste them into a Google Doc. What was interesting is how often I was asked if they could use songs with profanity, violence, etc. I simply responded that I wanted them to choose their all time favorite songs or the ones they listened to the most and if they didn't then the project wouldn't work.

Next we generated some Pseudocode. I asked them if you were to sit a small child down and tell him to write down how many times a certain word came up in a song what would you tell them?

This took about ten minutes of silent thinking, erasures, and debates so don't get the impression that they got it the first time (but who does).  Eventually the class came up with this.

1
2
3
4
Go through the song.
Each time you come to a word, check to see if that word has come up before.
If it has not, write the word down and a one next to it.
If it has, add one to the count/tally.

Next, we began to translate that into Python script. It gave me an opportunity to talk about data and dictionaries which is always a plus but when we were done, they had a big smile on their face as they realized how similar their pseudocode was to the actual code. To test the code as they were building it, we used Michael Jackson's Smooth Criminal as almost everyone knows it and in my opinion it has the most epic music video of all time. It also has some funky lyrics and punctuation that allows for refining the translate function.

The quick tutorial I gave them to learn about strings can be found here, but as I said this project will be refined as will the tutorial.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from string import *
song = '''Insert Lyrics Here'''

cleanString = song.translate(None,',.:;!?') #removes these characters
cleanList = cleanString.split() #splits it into a list
    
songDict = {}
for word in cleanList:
    if word not in songDict:
            songDict[word] = 1 #if not already in the dictionary, add it
        else:
            songDict[word]+=1 #if already in the dictionary, add 1 to it
    
print word, songDict[word] #option 1

for word in songDict: #option 2
    if songDict[word] > 1:
        print songDict[word]

The first option will print out the entire dictionary without any filtering. The second option was devised by the students after seeing how many times a word came up only once and will create a threshold to only print words that show up more than once (or more if they want). I love it when they come up with a solution like that!

After they saw the output, I asked them to reflect upon what significant words came up the most for them. For some it was "I, me, you, my" etc. which they saw as an indicator of songs about love and intimacy. Others were surprised how often a curse, violent, or derogatory word came up. Since their humanities teacher is teaching them how to write Sonnets and going through Romeo and Juliet, we ran those words through the code as well. Not surprisingly, the words were very intimate since they are both romantic literature.

Feel free to use the code to analyze your own songs and if you have any thoughts for next year's version of this I would love to hear about it in the comments. I hope to incorporate more of Pandora into the next iteration as I was informed that the software uses a form of the distance formula to decide which song to play next. Ha! Take that those who think Algebra is irrelevant.

Code formatting was made possible via Hilite.me. There are other great options out there but this was the quickest for me. It also made it easy for you to copy and paste the code for your own use. If you have a recommendation of how to do it better, please let me know.

Subscribe to BrokenAirplane and keep up with all of the latest education and technology resources!

Start Programming with Your Math and Science Class Today

If you are a long time reader of this blog, then you have seen the many ideas, thoughts, and examples of how I use and encourage the use of programming to learn math and science. I realized that I have not ever created a clear introduction to getting started with using Python in your class.

I hope that this tutorial helps you get started and have some great ideas. The more of us who are using and creating awesome math the more it helps everyone else. So please enjoy, ask questions, try something, and share with us what you did and how it went. It is exciting to think of all of the cool learning, questions, and skills that your students will gain from this experience.

Enjoy, and if you have any feedback or discover errors let me know. Here is a link to the PDF as well.

Subscribe to BrokenAirplane and keep up with all of the latest education and technology resources!

Programming and Puzzles in Math

One way I relieve stress with my students is with puzzles. We are currently preparing for our school wide exhibition "Festival del Sol". I'll be sure to follow up with pictures when it happens in a couple of weeks, it is amazing. Even though our students have done two exhibitions (the challenges of engineering project, and a Edgar Allen Poe play) there is still a high possibility of getting stressed out as the deadline approaches. I have a weekly puzzle on the board so we can take a moment to have some mathematical play.

I always choose puzzles that I do not know the answer to or that I have forgotten so I can enjoy working it out with the students as well. Often it inspires me to write a Python program to solve it. My students think I am cheating but I always tell them that someone has to program the computer, it can't just solve it for me.

This week's puzzle was:

Find the five digit number in which the first digit is two more than the second, the second digit is two more than the third, the fourth digit is two less than the third, and the last digit is two more than the fourth. The sum of the third, fourth, and fifth digits equals the first. The sum of all the digits is 19. What is the five-digit number?

Here is my solution, it is definitely one of the most nested loops I remember writing. Although I wasn't writing it for efficiency, I still reduced the loops to 9 because that is the biggest it could be for a single digit. I never cease to be amazed at how quickly the program can solve the problem.

1
2
3
4
5
6
7
8
for first in range(1,9):    
     for second in range(1,9):         
              for third in range(1,9):             
                     for fourth in range(1,9):                
                           for fifth in range(1,9):                     
                                if first+second+third+fourth+fifth == 19:                         
                                        if (first == second +2) & (second == third+2) & (fourth == third-2) &((third+fourth+fifth)== first):                                         
                                             print ("The answer is first: %i, second: %i, third: %i, fourth: %i, fifth: %i" % (first, second, third, fourth, fifth))   

Now for a real challenge. One of my favorite puzzles came from Henry Dudeney almost 90 years ago.

A college student sent a letter home to his parents saying, "Hey Mom and Dad, I need some more cash because college is expensive." The parents wrote him back saying, "We have spent all of this money to educate you and yet you ask us for money like this? You didn't even say how much you need." The student sends a letter back saying:

SEND + MORE = MONEY

Where each letter represents a unique digit from 0-9. How much money was the student asking for? Now you can of course Google the answer but I hope you will give yourself the time to either solve it by hand or program it.

Subscribe to BrokenAirplane for great tutorials and educational news.

How to Learn a new Programming Language with Students

Over the last half century, technology and electronics have become more and more complex and what they are capable of doing is simply phenomenal. Yet, for many students of science, the most instruction they receive in Electronics is the lighting of a light bulb or the turning of the motor. It is weird to me that we place electronics at the back of textbooks and curriculum preventing most educators from ever getting to it.

This is an incredible nexus in our history. The technology is amazing, but equally amazing is that the tools to create technology is within your students reach. Never before have their been so many free and relatively easy ways to learn a Programming Language (examples: Python, Google App Inventor, and Processing). Even the hardware is becoming cheaper with the Arduino, OLPC, and Makerbot. The point is that your students can create far more than ever before, and much of it with tools freely or cheaply attainable.

The question is how does one learn a programming language? I have had many discussions with our Spanish Teacher/Linguist on campus and it is clear to me that learning a programming language has some characteristics of learning a spoken language and many differences.

The essentials of learning a programming language
  • Motivation: The students must have an interesting goal or project. This process often requires high level abstract thinking and if they are not into it they will simply shut down. I often will have a demonstration or example of what we are going to do, or an interesting question that is best solved by a program. One example of this is how do you add up the numbers from 1-1000? (Yes I know of the Gauss method, but they often do not)
  • Access to resources. This means online videos, web based tutorials, forums, etc.
The combination of motivation + tutorials is what makes it possible to learn anything. If you have one without the other you are either going to drag them kicking and screaming or get wildly frustrated.

Developing Algorithms
Languages come and go but good algorithms last forever. I would rather they learn to transform a concept into an algorithm than become experts in any particular language. The way I frame this is by presenting a problem (e.g. generate Fibonacci numbers, primes, add two fractions with dissimilar denominators, etc) then asking them to explain it as if it were to a 3rd grader. 

This helps them break down the steps into very specific instructions. I will sometimes play the role of the child who misunderstands a seemingly simple command so they can refine it. Some might suggest using Pseudocode, I simply write it in English shorthand to make it as understandable as possible to the neophytes.

The trick is then helping them translate that to the language. I would not start with the above examples. First start with the Hello World exercises until they are able to get more complex and handle control structures (e.g. if-then-else statements) and looping.

Learning Syntax
Most often in programming languages and spoken languages, the difficulty is not in knowing what to say, but how to say it. When my students are learning a language, I will create or use one of the handy reference sheets found by Googling _________ reference sheet (fill in name of language). The Processing Language has a great reference sheet. Just make sure you adapt it to their needs so they are not overwhelmed. Here is one I made for Python Turtle.


If you really want to get programming with your students, the quickest way to get off and running is to go to the bookstore or go on Amazon and check out a book on programming that suits your needs. Don't be put off by the "dummies guides", I cannot tell you how much I have learned from them and they sit proudly on my bookshelf next to the other more technical books I was able to read afterwards.

Check out the exercises at the back of each chapter and feel free to use these in the classroom, like playing a musical instrument or writing in a journal, these exercises will challenge their minds and stretch their brains. You are doing a service to us all by helping spark an interest and I thank you!

Subscribe to BrokenAirplane!


Modeling Math with Python Programming: The Spirograph Program

Hopefully this software does not remind you of the intense amount of snow some of you are getting. I am often inspired by others to create software and when I was browsing the Math.com site one day, I found a beautiful Spirograph applet that I knew I had to try to recreate in Python. I try to impart this to my students, seeing something that you don't initially understand and learning as you go.

It required me to relearn Parametric Equations, refine my knowledge of Class Objects, learn the controlls functions in VPython and push the boundaries of my computer's memory.

In order to run this code you will need:
Python 2.6 - The interpreter for the code. Check out the programming page if you would like to know more about implementing Python or programming in your classroom.
VPython - The visual add on for Python.
Psyco - Speeds up the code significantly so I could run it on older laptops. If you don't want it or need it, feel free to delete the first couple of lines (before the "from visual")

Enjoy the pictures and the code below, and please share any great code you have or suggestions.





Spirograph Maker inspired by http://www.math.com/students/wonders/spirographs.html

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import psyco
psyco.full()
from visual import arange,curve,color,cos,sin,display,rate
from visual.controls import controls, slider,label

iterations = input('How many iterations?')

class spiro():
    def __init__(self,iterations):
        self.R = 65.0 #Radius of Fixed Circle
        self.r = 43.0 #Radius of Moving Circle
        self.o = 75.0 #offset of pen point in moving circle
        self.t = arange(0,iterations,1)
        self.drawing = curve(x = ((self.R+self.r)*cos(self.t) - (self.r+self.o)*cos(((self.R+self.r)/self.r)*self.t)), y = ((self.R+self.r)*sin(self.t) - (self.r+self.o)*sin(((self.R+self.r)/self.r)*self.t)), color = color.green)
    def fixedRadius(self,fRadius):
        self.R = fRadius.value
        self.redraw()
    def rollingRadius(self,rRadius):
        self.r = rRadius.value
        self.redraw()
    def penOffset(self,pOffset):
        self.o = pOffset.value
        self.redraw()
    def redraw(self):
        self.drawing.x = ((self.R+self.r)*cos(self.t) - (self.r+self.o)*cos(((self.R+self.r)/self.r)*self.t))
        self.drawing.y = ((self.R+self.r)*sin(self.t) - (self.r+self.o)*sin(((self.R+self.r)/self.r)*self.t))

class GUI():
    def __init__(self):
        self.c = controls(x=0,y=0,width=400, height = 400, range=100)
        self.s1 = slider(pos=(0,40),width=7, length=40, axis=(1,0,0),min=1,max=100,action=lambda:
                         Spirograph.fixedRadius(self.s1))
        self.s2 = slider(pos=(0,0),width=7, length=40, axis=(1,0,0),min=1,max=100,action=lambda:
                         Spirograph.rollingRadius(self.s2))
        self.s3 = slider(pos=(0,-40),width=7, length=40, axis=(1,0,0),min=1,max=100,action=lambda:
                         Spirograph.penOffset(self.s3))
        self.fixedRadiusLabel = label(pos=self.s1.pos, display = self.c.display, text='Fixed Radius', line = 0,
                                 xoffset=0, yoffset=20, height=10, border=0)
        self.rollingRadiusLabel = label(pos=self.s2.pos, display = self.c.display, text='Rolling Radius', line = 0,
                                   xoffset=0, yoffset=20, height=10, border=0)
        self.penOffsetLabel = label(pos=self.s3.pos, display = self.c.display, text='Pre-Offset', line = 0,
                               xoffset=0, yoffset=20, height=10, border=0)
        self.scene1 = display(title = 'Spirograph!', x=410, y=0, width=400, height = 400)
        self.scene1.select()

WYSIWYG = GUI()
Spirograph = spiro(iterations)

while(1):
    WYSIWYG.c.interact()


Subscribe to BrokenAirplane!