Comp 150-001, MWF 12:35, Crown 105

Week 1

Intro, ground rules. Two in-class exams and one final.
Fridays, and some Wednesdays, will be devoted to hands-on programming.

TA: Robert Kania


The language was initially developed by Guido van Rossum, and is named for Monty Python.

Why Python? It's the libraries! Ok, plus other things.

Start Idle (named for Eric Idle, one of the Monty Pythoners).

Be sure you're using Python3!

The first thing to notice is that python is completely interactive. You type expressions and definitions; it evaluates them and prints the result.

Homework 1, due Tuesday Jan 22

6: Make it handle numbers 'zero' through 'nine'.
8:  Find the product of the odd numbers between 1 and 100.
9:  Write a function triangle(n) to print the first n rows of this triangle made up of asterisks, shown here for n=4. You will need two loops: a for row in range(n): loop and an inner loop for col in range(row): . To print a single '*', use print('*', end=''). To start a new line, use print().


Python intro, from

1.3: Integers, strings, lists, None

1.4: Arithmetic, / versus //

1.5: Strings, +

1.6: Variables and assignment

1.7: print()

1.8: multiline strings

1.9: Idle

1.10: input(), string format()

1.11: defining functions

1.12: dictionaries

1.13: loops

Wednesday 1/16: function/loop definitions, installation

A couple functions:

Here is the happybirthday function from 1.11.4. Note the indentation; it must be consistent! Note the colon : at the end of the def line. Also note the way that the parameter person is incorporated into the body:

def happyBirthday(person):
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear " + person + ".")
    print("Happy Birthday to you!")

Second, here is a function that calculates the sum of the numbers from 1 to n. I could have used an input statement to get the value of n, but here I used a parameter. Note the colon at the end of both the def and for lines. Note the variable i introduced by the for line. Also, note that I used range(n+1), because range(n) goes from 0 to n-1. You can look at a range with list(range(n)).

def sum(n):
    sum = 0
    for i in range(n+1):
         sum += i
    return sum

Demo: Start Idle. Create a new file. Paste in happyBirthday(). Type in sum(). Note the automatic indentation. Save, and select Run module. Run both functions.

Is this function fast enough?

We can also write this with a while loop (though we haven't "officially" covered that yet):

def sum2(n):
    sum = 0
    while i <= n:
        sum += i
        i += 1
    return sum

Not everything has to be in functions. We can just type this at the top level:

for i in range(5):


The Python example collection is available at

Friday: dictionaries and lists. Here's a list with mixed data types (integers, strings, Boolean and floating-point)

la = [2, 3, 'five', True, 11.01]

We can now access elements by position:


Here's another list, auto-generated using range():

lb = list(range(1,10))
len(lb)    -> 9
lb[0]       -> 1
lb[8]       -> 8

We'll do more with lists later. For now, what we need are dictionaries. Like lists, you can retrieve a value by using its "index", but, unlike lists, the index can be strings, or almost any other type. The len() function gives, as with lists, the size of the dictionary.

Here is the [first] Spanish dictionary, found in the examples collection. It is not part of a function definition.

"""A tiny English to Spanish dictionary is created,
using the Python dictionary type dict.
Then the dictionary is used, briefly.

spanish = dict()
spanish['hello'] = 'hola'
spanish['yes'] = 'si'
spanish['one'] = 'uno'
spanish['two'] = 'dos'
spanish['three'] = 'tres'
spanish['red'] = 'rojo'
spanish['black'] = 'negro'
spanish['green'] = 'verde'
spanish['blue'] = 'azul'


Note the last two lines. These are examples of how we can use the dictionary to convert from an English string ("two") to a Spanish one ("dos").

For the time being, we're going to be using dictionaries only in limited ways. For example, here is the madlib program, also in the examples collection. The madlib program is built, partly, from functions:

String Substitution for a Mad Lib
Adapted from code by Kirby Urner

storyFormat = """                                      
Once upon a time, deep in an ancient jungle,
there lived a {animal}.  This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer.  One day, an
explorer found the {animal} and discovered
it liked {food}.  The explorer took the
{animal} back to {city}, where it could
eat as much {food} as it wanted.  However,
the {animal} became homesick, so the
explorer brought it back to the jungle,
leaving a large supply of {food}.

The End

def tellStory():                                    
    userPicks = dict()                             
    addPick('animal', userPicks)           
    addPick('food', userPicks)           
    addPick('city', userPicks)           
    story = storyFormat.format(**userPicks)
def addPick(cue, dictionary):
    '''Prompt for a user response using the cue string,
    and place the cue-response pair in the dictionary.
    prompt = 'Enter an example for ' + cue + ': '
    response = input(prompt).strip() # 3.2 Windows bug fix
    dictionary[cue] = response                                                            

input("Press Enter to end the program.")     

The program consists of a long string, storyFormat, and a dictionary. The storyFormat string contains a few keywords in braces, such as {animal}, {food}, etc. The dictionary contains "definitions" for these strings in the dictionary userPicks. If userPics['animal'] = elephant, then the storyFormat string is printed with each occurrence of {animal} replaced by "elephant".

This replacement is done using a special dictionary-aware option of the format function, the same format that we used in printing mixed strings and values:

print('the sum of {} and {} is {}'.format(x, y, x+y))

For now, though, all we are interested in is that this substitution works, and is based on dictionaries.