Week 1 Python Development Overview

Lecture

About Python

Python is the programming language that Sugar Labs has designated as the primary language for development on the OLPC XO laptop. Python's simplicity, ease of use, and power make it the ideal language for developing XO programs, called Activities.

Some quick facts about python:

  • Python is a High-level programming language.
    • Focus on programmer productivity and code readability
    • Minimalist syntax (see the section on this later)
    • Automatic Memory Management
    • Garbage-collected
    • Good support for object-oriented programming, but also has imperative and functional support
    • Good for creating applications, but also often used as a scripting language
  • Python is an Interpreted language
    • The Python interpreter is implemented in C (so are a few core libraries)
    • What might this say about speed?
    • What about threading?
  • What languages does Python remind you of at this point?

Getting/Running Python

  • You can download Python at Download Python Software
  • Running the binary will bring up an interpreter
  • Running a .py file will run the file

Syntax

  • Code taken from Python Tidbits
    • Go here for more Python examples as well
  • Look at the following code, and talk about what key syntax differences you might find with other languages
#    warmer.py        3/11/96 by Joe Strout

import rand        # handy random-number functions

def run():
    # pick a number in the range 1-100
    mynum = rand.choice( range(100) ) + 1

    yourguess = 200        # what user guessed
    lastdist = 0        # last distance to mynum
    tries = 0            # number of tries so far

    print "I'm thinking of a number from 1 to 100."

    # main loop: repeat until user gets it right
    while yourguess != mynum:

        tries = tries + 1
        yourguess = input("Your guess? ")

        if (yourguess != mynum):

            # find how far off you are
            newdist = abs(yourguess - mynum)

            # print warmer/colder than last time
            if (lastdist == 0):
                print "Guess again..."
            elif (newdist > lastdist):
                print "You're getting colder."
            else:
                print "You're getting warmer."
            lastdist = newdist

        # end of the if statement
    # repeat until user gets it right

    print "Good job!  That took", tries, "tries."

# immediate-mode commands, for drag-and-drop or execfile() execution
if __name__ == '__main__':
    run()
    print
    raw_input("press Return>")
else:
    print "Module warmer imported."
    print "To run, type: warmer.run()"
    print "To reload after changes to the source, type: reload(warmer)"

# end of warmer.py
  • First of all, what does this program do?
  • So what unique syntax do you recognize?
    • Scopes are defined by tabs, not brackets
    • End of line is end of syntax
    • Comments use #
    • while, for, if statements end in :, don't require parentheses around argument
    • def defines a function
  • Some others not shown in warmer.py
    • for statements iterate over a variable

Python Types

  • Partially adapted from Python Wikipedia Article
  • Variables are not type cast, they can contain any type
    • What does this mean for templating?
Type Description Syntax Example
str, unicode An immutable sequence of characters 'Wikipedia', u'Wikipedia'
list Mutable, can contain mixed types [4.0, 'string', True]
tuple Immutable (once set, its contents cannot be changed), can contain mixed types (4.0, 'string', True)
set Unordered, contains no duplicates set([4.0, 'string', True])
dict Group of key and value pairs {'key1': 1.0, 'key2': False}
int A fixed precision number (will be transparently expanded to an unlimited precision long, when it overflows the storage for an integer.) 42
float A real number 3.1415927
complex A complex number with real number and imaginary parts 3+2j
bool truth value True or False

Assignment

Teacher solution

import string
import copy

def stringToList(strang):
        dalist=[]
        for x in range(0,len(strang)):
                dalist.append(strang[x])
        return dalist

def getSubStrings(full_word,curr_word,used_list):
        substrings=[]
        for x in range(0,len(full_word)):
                if used_list.count(x)==0:
                        new_curr_word = curr_word+full_word[x]
                        new_used_list = copy.copy(used_list)
                        new_used_list.append(x)
                        substrings.append(new_curr_word)
                        substrings.extend(getSubStrings(full_word,new_curr_word,new_used_list))
        return substrings

#A recursive solution
def getWordsR(word):
        substrings=getSubStrings(word,"",[])
        substrings.sort()

        x=0
        y=0

        words=[]
        while x<len(dictionary) and y<len(substrings):
                while x<len(dictionary) and substrings[y]>dictionary[x]:
                        x+=1

                if x<len(dictionary) and dictionary[x]!=word and substrings[y]==dictionary[x]:
                        words.append(substrings[y])

                y+=1

        return words

#An iterative solution
def getWords(word):
        words = []
        lessthanequalword = []
        for i in range(0,len(dictionary)):
                if len(dictionary[i]) <= len(word):
                        lessthanequalword.append(dictionary[i])

        for j in range(0,len(lessthanequalword)):
                if inword(lessthanequalword[j],word) and word != lessthanequalword[j]:
                        words.append(lessthanequalword[j])

        return words

def inword(subs, words):
        sub=stringToList(subs)
        word=stringToList(words)

        sub.sort()
        word.sort()

        i = 0
        j = 0

        while j < len(sub):
                if i == len(word):
                        return False

                if word[i] > sub[j]:
                        return False
                elif word[i] == sub[j]:
                        i += 1
                        j += 1

                elif word[i] < sub[j]:
                        i += 1

        return True     

dictionary=[]
file = open("lowerwords.txt",'r')

for line in file:
        dictionary.append(line.strip())

file.close()

dictionary.sort()

word="testword"
#print getWordsR(word)
#print getWords(word)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License