Introduction to Programming (Oct-Nov 2011)


Before the course

Day 1 (October 20th)

Day 2 (October 27th)

Day 3 (November 3rd)

Day 4 (November 10th)

Day 5 (November 17th)

These courses notes are licensed under the CC-BY license. Please include my full name and link to this site if you share, remix or reuse this work. I wouldn't mind either if you let me know about it after you're done :)

Note: If you're only looking for exercises for your own courses, don't worry about the license and just grab them. Please feel very free to share back in exchange any exercise or resources you found useful elsewhere -- I always struggle to find more!

Before the course

Please try to install Python and the programming environment following the steps below before the course, so we can start on the interesting parts as soon as possible. If you get stuck, no worries, we will sort it out on the day.

Installing Python

We're going to be working with Python 2. If you have any Python version > 2.5, you're fine.

  • Linux: Python should already be installed. Type "python --version" into a command line to check that you're using a version of Python 2.
  • Mac: Python should already be installed with Mac OS X. Try typing "python --version" in the Terminal application to make sure.
  • Windows:
    • Download Python from the official website.
    • Install the executable
    • Make sure to update your PATH environment variable with your Python path. In My Computer -> Properties -> Advanced -> Environment Variables, Find the variable named "PATH" and at the end, add the path where Python installed -- it should be something like C:\Python27\

Installing the programming environment

To simplify programming, I'd like us to use an IDE (Integrated Development Environment). If you're already familiar with another IDE or text editor, please use instead what you're already familiar with.

  • Linux

Option 1 (Recommended): Please install Geany, it should be in your repositories (look in Synaptic, for Ubuntu).

Option 2: IDLE, which is installable from the repositories as well.

Option 3: gedit is perfectly fine.

  • Windows

Option 1 (Recommended): Please download and install Geany.

Option 2: Use IDLE, installed by default with Python (somewhere like c:\python27\idlelib\idle.pyw)

Option 3: Notepad or some sort of text editor with syntax highlighting is perfectly fine as well.

  • Mac

Unfortunately, I don't believe it's possible to run Geany on a Mac. We will be using IDLE, which should be installed by default... Just in case and if you can't find IDLE on your machine, please download and install the Python executable, it will be included.

Note: If you're running Mac OS X 10.6 there might be an issue where IDLE crashes a lot. Have a look here and download the latest version of Tcl/Th for your machine to resolve it.

Another note: I don't have access to a Mac, which limits my ways of testing an IDE. If anyone has Xcode installed (requires free registration), or has the time and inclination to download and install it before we meet, I would love to have a quick look and check if it's appropriate for the course. Get in touch!

Thursday, October 20th

Setting up the programming environment

  • In Geany: go to Edit -> Preferences -> Editor -> Indentation. Set the tab width to 4 and "Type" to spaces. This is to avoid mixing tabs and spaces, which can create confusion.
  • In Geany: to run a program, click on the Execute icon. It looks like little cogs.
  • In IDLE: to create a new program, go to File -> Window -> New Window. To run it, go to Run -> Run Module.

Creating a new Python file

A Python file must end with .py and the name cannot contain spaces.


Displaying text on the screen

print "Hello, world!"

The double quotes means this is a string, a piece of text. Single quotes work too.


name = "Bob"
print "Hello", name

A variable works like a box. You give it a name (here, "name") and then you declare what you want the variable to contain. Whatever is on the right of the = sign ("Bob"), will go into the variable as named before the equal sign (name). In the example, from now on, wherever we use name without quotes, we will actually be using the value we put inside it: "Bob".

This is called "assigning a variable." You can have as many variables as you want! Restrictions are similar to file names: they cannot contain spaces (underscores are ok) and shouldn't start with a number.

Also, you might notice that we move to a new line to print the variable: in Python, you can only have one command per line.

Variable types

Try this:

print 2 + 2
print "2 + 2"
print "2 + 2 = ", 2 + 2

You can force a variable or a piece of text to be treated as a number, rather than as text, by using the function int():

print int("2") + int("2")

Variables bingo

a = 1
a = "elephant"
print a

a = 3
b = 4
b = a
print b

a = "Python"
b = "is"
c = "cool"
d = c, b, a
print d

Getting input from the user

name = raw_input("What's your name? ")
print "Hello", name

raw_input() will always return a text value. If you're expecting a number you will have to convert it using int().

If condition

Be mindful of:

  • the indentation, and make sure to keep it consistent
  • the colon at the end of the "if" statement and after the "else"
number = raw_input("Please enter a number: ")

if int(number) > 5:
    print "Number is higher than 5."
elif int(number) < 5:
    print "Number is lower than 5"
    print "Number is 5."

print "This text will be displayed all the time, because there is no indentation."

To combine conditions:

if int(number) > 5 and int(number) < 10:

Operators to work with numbers

+   addition
-   subtraction
*   multiplication
/   division

Comparison operators

>    Greater than
>=   Greater than or equal to
<    Less than
<=   Less than or equal to
==   Equal
!=   Not equal


5 exercises, of 3 types:

- Adapt the behaviour of an existing working program, so that it does something else as per the instructions (1 exercise: A)

- Fill in the blanks (1 exercise: B)

- Write this program from scratch (3 exercises: C, D, E)

# # #


This program works:

rate = int(raw_input("Please enter the rate (%): "))

if rate < 50:
    print "Mediocre"
elif rate < 80:
    print "Ok"
elif rate <= 100:
    print "Great!"

1. Change this program so that a rate under 5 writes "Boo!" on the screen.

2. Change this program so that everything between 15 and 80 is "Ok".

3. Change this program so that "100" prints "Perfect!"

# # #


Fill in the blanks so that this program works correctly:

age = raw_input(.................)
country = ............("What is your country? ")

if country ....   ..............:
    if int(age) >= 18:
        print "You can vote"
        print "You cannot vote"

if country == "Fiji":
    if int(age) < 21:
        print .................
        print .................

if country != "Ireland" and country != "Fiji":
    print "I don't know"


  • You can vote from 18 in Ireland
  • You can vote from 21 in Fiji

# # #


Ask the user for a user name and a password. If the user types the correct combination, display "Welcome!" otherwise display "Wrong user name or password."

Example program output (bold is data entered by the user):
Username? no one
Password? passw0rd
Wrong user name or password.

Example program output (bold is data entered by the user):
Username? Ulysse
Password? passw0rd


Write a text user interface similar to the following, that shows a menu with a few options to the user. When the user types in "a", "b", or "c", a different response is displayed on the screen.

|                                     | 
|         HELLO!                      | 
|       /                             | 
|    \O         Choose an             | 
|     |\             option           | 
|    / \                              | 
|                                     | 
|              a. Say hi              | 
|              b. Say goodbye         | 
|              c. Fortune cookie      | 


Write a program to find out whether a year is a leap year. A year is a leap year if it is divisible by 4, but not by 100 unless it can be divided by 400 as well.

For example: 

  • 1992, 1996, 2000, are leap years.
  • 1993, 1900, 2010 are not leap years.

Example program output (bold is data entered by the user):
What year? 1996
1996 is a leap year.


  • To have several conditions in an if statement, you can use the word "and" (see exercise B for an example).
  • To get the remainder of a division, you should use the operator %. It's called "modulo" and has nothing to do with percentages (just to be confusing!). An example of how it's used:
print 5 / 3    # prints "1" on screen. 5 divided by 3, result is 1
print 5 % 3    # prints "2" on screen. 5 divided by 3, remainder is 2

Sample answer (D)

Here's a possible answer for exercise B. There is more than one way to do it. Feel free to drop me a mail if you're stuck or would like a sample answer for another one.

print "______________________________________"
print "|                                     |"
print "|         HELLO!                      |"
print "|       /                             |"
print "|    \O         Choose an             |"
print "|     |\             option           |"
print "|    / \                              |"
print "|                                     |"
print "|              a. Say hi              |"
print "|              b. Say goodbye         |"
print "|              c. Fortune cookie      |"
print "|_____________________________________|"

option = raw_input()

if option == "a":
    print "Hi!"
elif option == "b":
    print "Good bye!"
elif option == "c":
    print "He who never made a mistake, never made a discovery."

Sample answer (E)

year = int(raw_input("What year? "))

if year % 4 == 0 and (not year % 100 == 0 or (year % 100 == 0 and year % 400 == 0)):
    print year, "is a leap year."
    print year, "is not a leap year."

Thursday, October 27th

The interpreter

Open the command prompt on Windows (Start -> All programs -> Accessories -> Command prompt) or Terminal application on Mac OS X and Linux.

Type in 'python'. Thanks to the path changes we made on the first day, this will open the Python interpreter. Here you can try Python code.

Type 'exit()' to leave.

Working from the command line

If you aren't using Geany but a text editor for instance, or just out of curiosity you might like to know how to execute a Python program from the command line.

Super quick command line tutorial:

  • cd stands for change directory and you navigate by typing cd my_folder_name
  • dir (ls for Linux/Mac OS X) will list what is in a directory

Using cd, go to a directory where you have a program. You can then execute the program in the command line by typing python

This is what Geany is doing for you with the wonderful "Execute" button :)


You can leave comments in your code by starting a line with the pound sign (#). This is intended for humans reading your program and Python will ignore it.

# This is a comment,it is meant for humans and will not be interpreted by Python
# Every comment line must begin with a #
print "Hi!" # You can write a comment after a programming instruction

While loop

A while loop will keep executing while the condition is true.

For instance, this will keep adding 1 to the variable count, while i is less than 5:

count = 0
while count < 5:
    count = count + 1
print "End of the loop, count is now:", count

Note the indentation, which is very important just like for an if statement.

Loops can be tricky, if you don't think about them carefully you might end up with an infinite loop! For instance, this loop will never end:

while 1 + 1 == 2:
    print "Oops... This loop will never end."

"Guess the number" game

import random 

solution = random.randint(1, 10) # Random integer between 1 and 10
max_guess = 5
number = raw_input("Guess the number: ")
guess = 1

while int(number) != solution and guess < max_guess:      guess = guess + 1      if int(number) < solution:          print "Wrong guess (too low). Please try again."      else:          print "Wrong guess (too high). Please try again"      number = raw_input("Guess the number: ") if int(number) == solution:     print "Congratulations! You guessed the number right." else:     print "You've reached the maximum number of guesses. The number was", solution
  • "While" kind of works like "If". It's followed by a condition, and can contain multiple conditions using and and or. The content (also called the "body" of the loop) is marked by indentation. The loop keeps executing while the condition is true. The body of the loop is skipped when the condition becomes false.
  • Beware the infinite loop!
  • "random" is a Python library that contains useful functions to play with numbers. To see what other interesting functions it contains, you can go to -> Global Module Index -> R -> random. It's part of Python ; however because it's not part of the "main" language we need to import it first. Python offers a ton of useful libraries that can do tons of useful things, but they can't load everything all the time or every program would take a very long time to start. By writing "import random" at the very top, we tell Python to load the "random" functions, in addition to the main Python stuff.



This program works:

word = ""
value = raw_input("Please enter a letter: ")
while value != "":
	word = word + value
	value = raw_input("Please enter a letter: ")
print word

Try it a few times, to understand how it works. Then...

1. Change this program so that the program stops when the user enters the letter "a"

2. Change this program so that it shows the letter in reverse: that is, if the user entered "b", then "c", then "d", the final word displayed is "dcb" instead of "bcd".


Ask the user for a number, until the user enters 0. Then add all the numbers and display the total.

Example program output (user input is in bold):
Enter a number (0 to end): 5
Enter a number (0 to end): 1
Enter a number (0 to end): 14
Enter a number (0 to end): 0 
Total is: 20


Ask the user for a user name and password. This time, the user gets 3 attempts in case they get it wrong.

Example program output (user input is in bold):
Username? me
Password? hello
Wrong user name or password. Please try again.

Optionally: Tell the user how many attempts they have left. Hint: Use str(variable_name) to concatenate string and number, for example: 

print "My favourite number is " + str(my_number)


Ask the user how many values they want to enter. Then get the number of values asked for and display the average.

Example program output (user input is in bold):
How many values to enter? 3
Enter value: 98
Enter value: 52
Enter value: 27
Average is: 59


Remember this?

|                                     | 
|         HELLO!                      | 
|       /                             | 
|    \O         Choose an             | 
|     |\             option           | 
|    / \                              | 
|                                     | 
|              a. Say hi              | 
|              b. Say goodbye         | 
|              c. Fortune cookie      | 

Add  a fourth option: "q. Quit" and change the program so that the user can keep choosing an option, until they choose option "q" and the program exits.

Sample answer (A)


word = ""
value = raw_input("Please enter a letter: ")
while value != "a":
    word = word + value
    value = raw_input("Please enter a letter: ")
print word


word = ""
value = raw_input("Please enter a letter: ")
while value != "":
    word = value + word
    value = raw_input("Please enter a letter: ")
print word

Sample answer (B)

total = 0

number = raw_input("Enter a number (0 to end): ")

while int(number) != 0:
    total += int(number)
    number = raw_input("Enter a number (0 to end): ")

print "Total is:", total

Sample answer (C)

This includes the optional extras!

max_attempts = 3
username = "Ulysse"
password = "passw0rd"
user = ""
passw = ""

attempts = 0

while attempts < max_attempts and username != user and password != passw:
    user = raw_input("Username? ")
    passw = raw_input("Password? ")

    if user == username and passw == password:
        print "Welcome!"
        attempts += 1
        print "Wrong user name or password. " + str(max_attempts - attempts) + " attempt(s) left."

Thursday, November 3rd

Code reading

What does this do?

count = -1

while count <= 0:
    count = int(raw_input("What's the countdown? "))

while count > 0:
    print count
    count = count - 1

print "TADAM!"

Boolean logic

All conditions must evaluate to True or False. For instance in an if statement, "if number > 5:", number > 5 is the condition. If the condition is True, the if statements executes the content of its block, otherwise it skips it and goes to the else: section. Likewise, a while loop will keep executing while its condition is True, and we jump to the code outside of the loop block when the condition evaluates to False.

Now, boolean logic:

if True and True...    =>"True"

if True and False...   =>"False"

if True or True...      =>"True"

if True or False...      =>"True"

Now, when we add parenthesis it works like in arithmetic, what's in the parenthesis is evaluated first. Does this evaluate to True or False?

if True and (True or False)...    ...??

if True or (True and False)...    ...??

(Answer: they both execute!)


  • Lists are also knows as "arrays"
  • They give us a way to store multiple values into a single variable
  • Be careful: to access an element within the list, you need to start counting from 0
  • Note the square brackets!
restaurants = ["Fafie's", "Eden", "TGI Friday", "McDonald's"]
adjectives = ["great", "awesome", "poor", "yucky"]

print restaurants[0], "is", adjectives[0]

For loops

For loops give us a more efficient and convenient way to go through every element of a list.

restaurants = ["Fafie's", "Eden", "TGI Friday", "McDonald's"]
adjectives = ["great", "awesome", "poor", "yucky"]

print "There are", len(restaurants), "restaurants"

for my_restaurant in restaurants:
    print my_restaurant

For vs. While

  • While is better when you're waiting for something to happen, for a condition to become true
  • For is better when you know the number of elements you want to look at in advance, for instance everything in a list

len() is a function that tells you how many elements there are in an array (the name is short for length). It's usually good practice to use it rather than type numbers directly, so when you add or remove items in your list, the rest of the code picks it up automatically rather than having to change a number in multiple places.

More For loops

restaurants = ["Fafie's", "Eden", "TGI Friday", "McDonald's"]
adjectives = ["great", "awesome", "poor", "yucky"]

for i in range(0, 4):
    print restaurants[i], "is", adjectives[i]
# The same, but using best practices:

for i in range(0, len(restaurants):
    print restaurants[i], "is", adjectives[i]
  • i is a common short variable names used in loops. It stands for "index", the number that represents the position of the element in an array
  • range(start, end) creates a list of numbers starting at the number specified first, to the second number (but not including it). For instance: range(0, 4) returns this list: [0, 1, 2, 3]

Exercise solution: Choose a random adjective to display besides each ingredient

import random

restaurants = ["Fafie's", "Eden", "TGI Friday", "McDonald's"]
adjectives = ["great", "awesome", "poor", "yucky"]

for restaurant in restaurants:
    choice = random.randint(0, len(adjectives)-1)
    print restaurant, "is", adjectives[choice]


Think Python: How To Think Like A Computer Scientist is a book that you can read for free online (or buy a hardcopy), that goes much more thoroughly through the material we've covered (and more!), and teaches other useful skills in parallel such as debugging. There are exercises, and if you want to go beyond the course when it's finished this is the book I would recommend. Looking at different explanations for what we've seen so far might also be useful!



Fill in the blanks (.....) so that the program works.

restaurants = ["Fafie's", "Eden", "TGI Friday", "McDonald's"]
adjectives = ["great", "awesome", "poor", "yucky"]
for restaurant in restaurants:
    print restaurant, "is?"

    for i in range(.....):
        print i, "-", ......[...]

    choice = raw_input()

    print ....., "is", .....[int(choice)]

What the program should do is:

  • For each restaurant, display the list of all possible adjectives,
  • Then -- still for each restaurant -- ask the user to choose the adjective they want.


Redo any (or all!) of the "While" set of exercises marked with a *, this time using a "for" loop to solve the problem.


You have a list of numbers. Print the largest number from the list. Extra: Make sure it also works when the list only contains negative numbers.

Example program output:
List is: 0, 7, 9, 15, 8
Largest number is 15

Example program output:
List is: -15, -2, -4, -9
Largest number is -2


Print the multiplication tables from 2 to 10, using two 'for' loops. (Note: Your final program shouldn't be any longer than 5 or 6 lines!)

Hint: If you're not sure where to start, start by writing the multiplication table for only one number, say 5, using one 'for' loop.


Ask the user for a number between 1 and 12. Print the month associated with the number.If the user enters an incorrect number (0, 13, 24, ...), display an error message.

Example program output (user input is in bold):
Please enter a number between 1 and 12: 9
Month is: September

Sample answer (A)

restaurants = ["Fafie's", "Eden", "TGI Friday", "McDonald's"]
adjectives = ["great", "awesome", "poor", "yucky"]
for restaurant in restaurants:
    print restaurant, "is?"

    for i in range(0, len(adjectives)):
        print i, "-", adjectives[i]

    choice = raw_input()

    print restaurant, "is", adjectives[int(choice)]

Sample answer (B)

numbers = [0, 7, 9, 15, 8]
largest = numbers[0] for number in numbers:     if number > largest:         largest = number print "Largest is:", largest

In bold is the line you should change to solve the "optional" part of the exercises. (The approach is, if you initialise the variable 'largest' with an element of the list, you ensure the result will always be correct even if it's all negative numbers.)

Sample answer (C)

for i in range(2, 10):
    for j in range(2, 10):
        print i, "*", j, "=", i*j

Thursday, November 10th

Code reading

strange_list = ["one", "potato", "", "bread", "red", ""]
has_empty_entries = False

for entry in strange_list:
if entry == "":
has_empty_entries = True
break if has_empty_entries: print "Error."
  • True/False: boolean variable (note how the first letter is a capital letter)
  • if has_empty_entries is a shortcut for if has_empty_entries == True
  • break was added later on in the example, and is meant to "break" out of the loop when encountered (so for instance you don't need to go through the 10,000 items in a list if you found what you wanted at the beginning).

String manipulation

We've seen and used strings a lot so far. Let's see what the Python documentation has to say about it. Go to Go to Library Reference, and find strings. You can see "str" is in sequence types, just like a list: this means there are a lot of list operations you can do on a string, for instance:

sentence = "Python is cool"
for letter in sentence:
    print letter
  • The major difference is that strings are immutable. You can read them, but you can't change them: sentence[0] = "L" will fail (try!)
  • Still, looking at "Operations" there is a lot of things we can do. Testing from the interpreter:
>>> sentence = "Python is cool"
>>> print sentence[0:6]
>>> print sentence[1:6]
>>> 'a' in sentence
>>> 'o' in sentence
>>> sentence.index('n')
>>> sentence.count('n')
>>> sentence.count('o')

Then looking further down in the documentation, we see "String methods," which is where we'll spend most of our time for the exercises, and in general. Let's have a look at replace.

>>> sentence.replace("Python", "Cake") 
'Cake is cool' 
>>> print sentence 
Python is cool 
>>> sentence = sentence.replace("Python", "Cake") 
>>> print sentence 
Cake is cool 
>>> sentence = sentence[0:4] + "nom!"
>>> print sentence 

Remember, strings are immutable. When you call "replace" it actually creates a new string. Therefore if you want to change your sentence, you need to assign it to itself (e.g. sentence = sentence.replace("Python", "Cake")) or create a new variable to store it.

File handling (Writing)

file = open('things.txt', 'w')

thing = raw_input("Enter the name of something you like: ")

while thing != "":
    file.write(thing + "\n")
    thing = raw_input("Enter the name of something you like: ")

  • The 3 modes are 'r' (Read), 'w' (Write), 'a' (Append). Try with different modes to see the difference.
  • \n is a special character that creates a new line. Try without it.
  • Always close resources, or you'll have some unpleasant surprises with files being locked, or data not being written.

File handling (Reading)

f = open('things.txt', 'r')
things = f.readlines() f.close() print "There are", len(things), "nice things" for t in things:     print t.strip()
  • readlines() will take everything from a file and put it into a list, with one line of the file in each list item.
  • readline() can be used to read only one line at a time. You'd use it in a while loop.
  • strip() is described in the documentation. Try with and without it.


Invent Your Own Computer Games with Python is another nice book that goes through the basics (and more) for beginners. It's a nice one to use because the examples and exercises are about building simple games (think hang-man or tic-tac-toe, rather than Call of Duty though). I've been known to borrow exercises from the book, and would recommend it in addition to last week's "How to Think Like a Computer Scientist".

Exercises (String manipulation)


Get a word from the user. Check if the word is a palindrome. (A palindrome is a word that is the same no matter which side it is read from, for example "Mom", "noon", "radar".) Extra: Make sure it works even if the case is different (e.g. "Mom")

Strategy hint: If you're not sure how to go about this, here's a possible approach: create a new variable where you will store the reverse of the word (we've done this before! Think, showing "dcb" instead of "bcd"...). Then you can compare the 2 variables and if they are the same, the word's a palindrome!


Get a sentence from the user. Rewrite it with the first letter of every word capitalised and the rest of the word in lower case.

Examples of program output (user input is in bold):
Please enter some text: pyTHon is COOL
Python Is Cool


Ask the user for a number. Check that the user really gave you a number, removing everything that is not a number (so that the int() conversion would work). If there was no number in the input, write an error message.

Examples of program output (user input is in bold):
Please enter a number: b7er
Number is: 7
Please enter a number: abcdef
This is not a number!


Get some text from the user. Check if the input is in alphabetical order.

Examples of program output (user input is in bold):
Please enter some text: abef
Not alphabetical.
Please enter some text: abcdef
Input is in alphabetical order.


Ask the user for a sentence. Count the number of words in the sentence.

Example program output (user input is in bold):
Enter a sentence: Ask the user for a sentence. Count the number of words in the sentence.
Number of words:  14

Sample answer (A)

word = raw_input("What's the word? ")

rev = ""

for letter in word:
    rev = letter + rev

if rev.lower() == word.lower():
    print "Palindrome"
    print "Not a palindrome"

Sample answer (C)

number = raw_input("Enter a number: ")
num = ""

for item in number:
    if item.isdigit():
        num += item

if len(num) == 0:
    print "This is not a number!"
    print "Number is: ", int(num)

Sample answer (D)

word = raw_input("Please enter some text: ")

alpha = True

for i in range(len(word)-1):
    if word[i].lower() > word[i+1].lower():
        alpha = False

if alpha:
    print "Alphabetical order"
    print "Not alpha"

Exercises (File handling)


You have 2 files to start with. They each contain a series of numbers. Read from both files at the same time, and add each number together. Write the results in a third file.

For example, if file1.txt contains:

and file2.txt contains:

You should end up with a results.txt file like this:

Tip: Just like int(variable) transforms a piece of text (string) into a number (integer), str(variable) will transform a number into text. You can only write text in a file.


You have a file with a list of questions and answers. Every question is followed by its answer on the next line, like this:

Who is the current Irish president?
Michael D. Higgins
What's the biggest book store in Ireland?
Hodges Figgis
What's the capital of Germany?

Your program should read in this file and select a random question, and ask it to the user. If the user answers correctly, display "Won!" on screen. If the file is edited the new questions should automatically be picked up.

Tip: You'll likely find that even when writing the correct answer your program says the answer is incorrect. Remember your string manipulation tips! Reading a file includes the "\n" add the end of each line: you can either find which string function will help you remove this (best solution!), or compare against the user's reply + "\n" (for instance, if your variable name is "answer", compare against: answer + "\n").

Sample answer (B)

import random

file = open('questions.txt', 'r')
questions = file.readlines()

rand = random.randint(0, (len(questions)/2)-1)

answer = raw_input(questions[rand*2])

if answer + "\n" == questions[rand*2+1]:
    print "Win!"
    print "Lose! Answer was:", questions[rand*2+1]

Thursday, November 17th

Code reading

What will this print? Read the documentation on rstrip().

sentence = "Python is cool"

print sentence.rstrip("l") # Python is coo
print sentence.rstrip("ol") # Python is c
print sentence.rstrip("o") # Python is cool


def sayHi():
    print "Hi!"

def sayHello(name):
    print "Hello", name

def square(number):
    result = number * number
    return result

def add(n1, n2):
    result = n1 + n2
    return result


print square(2)
print square(3)
print square(4)

print add(1, 2)
print add(3, 4)
  • A function is a self-contained section of code that can be reused over and over, which is useful to structure your code.
  • Between the parenthesis are the parameters, also called arguments. These are variables that will contain the value you use to "call" the function.
  • A function must be defined before you can use it.
  • The content of a function is ignored until the function called -- if you remove all the statements after the last "return result", nothing will happen when executing the file.
  • "return" enables us to use what the result of the function -- here we print it, but we could also store in a variable to use later.


You can now create your own libraries of functions to import into your programs. If the name of the file where you defined your square() function is, you can use it as follow from another file:

import mycoolfunctions
print mycoolfunctions.square(5)

(The files should be in the same directory.)

Code reading

What will be displayed on screen at line 12 (in bold)?

file = open("mycoolfile.txt", "w")
file.write("Hello,\n world\n!")

count = 0

file = open("mycoolfile.txt", "r")
for line in file:
    count += 1

print count

Give a think, then you can keep reading this sentence for a hint... hint... hint... The answer is the number three. Can you explain why?



Fill in the blanks so that this program works correctly:

def is_valid_phone_number(number):
    if number.isdigit():
        return True
        return False

def ...................(name):
    if name..........():
        return True
        return False

print is_valid_phone_number("0871234567") # True
print is_valid_phone_number("abcdef") # False

print is_valid_name("Martin") # True
print is_valid_name("Martin003") # False

print .............("Melody") # False


A few weeks back we wrote a small program that displays on screen the multiplication tables from 2 to 10. Based on the same idea, write a small function that takes a number as a parameter, and prints the multiplication table for that number from 2 to 10.


Write a function that takes a number of seconds as a parameter, and returns a string "translating" that number into hours/minutes/seconds.

Example output, if your function is named "hours" and your program reads:

print hours(3600) 
print hours(1) 
print hours(74) 
print hours(7283) 

Running your program should result in the following output:

1h 0mn 0s 
0h 0mn 1s 
0h 1mn 14s 
2h 1mn 23s 

Sample answer (A)

def is_valid_phone_number(number):
    if number.isdigit():
        return True
        return False

def is_valid_name(name):
    if name.isalpha():
        return True
        return False

print is_valid_phone_number("0871234567") # True
print is_valid_phone_number("abcdef") # False

print is_valid_name("Martin") # True
print is_valid_name("Martin003") # False

print is_valid_phone_number("Melody") # False

Sample answer (B)

def multiplication(number): 
    for i in range(2, 11): 
        print number, "x", i, "=", (number*i) 


Did you like the exercises and would like more of the same type? Have a look at CodingBat.

Google has a Python video course, if learning with video is more of your thing (I haven't checked out that course myself, but some people recommend it.)

Danielle also shared with us the MIT Intro course which uses Python. There are videos, assignments and exam papers.


I took an opportunity to show how Python could also be used to control a robot :-) The robot in question was the Finch, and the code snippet was as follows:

import edu.cmu.ri.createlab.terk.robot.finch.Finch as Finch

darwin = Finch()

Thank you!

Thank you all for attending! I really enjoyed teaching the class. I'll be holding Python Office Hours in Tog on December 1st, if you have questions or would like to work on more exercises which someone who can help you if you get stuck at hand.

Happy programming!