Introduction to programming, with Python (Aug-Sept 2010)

Welcome!

Day 1 (Monday, August 23rd)

Day 2 (Monday, August 30th)

Day 3 (Monday, September 6th)

Day 4 (Monday, September 13th)

Day 5 (Monday, September 20th)


These courses notes are licensed under the CC-BY-NC license.

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! Add a comment or contact me directly.


Monday, August 23rd

Installing Python

  • Linux

It's already installed :)

  • Mac

It's already installed, but let's install 2.6 from Python.org to get the IDLE program installed as well: see Python documentation for more information, and this link to download.

  • Windows

See option 2 on that page for more information. The link to download has actually moved there since then. For Windows XP or if those instructions don't work, look at the Python documentation for Windows.

Installing the Integrated Development Environment (IDE)

  • Option 1: Geany

If at all possible, I recommend installing Geany.

Linux: Under Linux, it will be in your repository (look in Synaptic, for Ubuntu.)

Mac: There are some instructions on how to install it under Mac using DarwinPort but unless you have the main DarwinPort application already installed I don't recommend following that route.

Windows: Geany is available under Windows but I don't know how well it will actually work. You should add your Python installation folder to your Path environment variable.

  • Option 2: IDLE

IDLE is easily available under all 3 platforms. It's less good that Geany but will do the job well enough for this course. It should have come preinstalled with Mac and Windows if you followed the instructions to install Python above.

On Windows, it's located in there: c:\python26\idlelib\idle.pyw.

For Linux users, if you're curious to have a look it's available in the repositories as well.

First programming steps

Displaying text on screen

print "Hello, world!"

Using a variable, variable assignment ( = )

name = "Bob"
print "Hello", name

Getting user input

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

Comment

# This is a comment, not interpreted by Python
# Every comment line must begin with a #
print "Hi!" # You can write a comment after a programming instruction

If condition

Be careful about:

  • the indentation, and 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) > 999:
    print "This is a big number."
else:
    print "This a small number."

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

The int() around the variable in the previous example, is to ensure Python will treat whatever is in the variable as a number, rather than as text.

Comparison operators

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

Monday, August 30th

See write-up from previous day for various useful reminders.

Refresher exercises (if)

We started with a couple of exercises to review, remember and reinforce what we did last week. The idea is to finish at least one before we move onto new things.

A.

Ask the user for 2 strings (text) and 2 integers (numbers).

Concatenate the 2 strings, multiply the 2 integers and display the results to the user.

Example program output (bold is data entered by the user):

Enter first word: class
Enter second word: room
Enter first number: 4
Enter second number: 3
classroom
12

B.

Write a text user interface like the following, offering a few options to the user. An appropriate response should be output after the user types in an option.

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

Use any proverb you like for option "c"!

C.

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.

Tips:

  • To have several conditions in an if statement, you can use the word "and", for example:
        if number > 1 and number < 5:
            print "Hello"

To get the remainder of a division, you should use the operator % (called modulo). 

print 5 / 3    # prints "1". 5 divided by 3, result is 1
print 5 % 3    # prints "2. 5 divided by 3, remainder is 2

Sample answer (B)

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 (C)

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."
else:
    print year, "is not a leap year."

New concept: 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."

As an exercise, you can try to change exercise B above, to let the user try any option, until they type in "q" to quit the program.

"Guess the number" game

We worked on a game, that we enhanced along the evening until we arrived at something similar to this.

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 

Random is a library function. We don't need to go into details right now, but if you wanted to know more (and more than you would ever want to know!) about the possibilities of 'random', you can go to the Python documentation site, looking at the "Global Module Index" then searching for 'random'. It's a lot right now, but later on when you write your own programs it'll be handy to remember how to navigate the documentation.

While exercises

We did not have time to look at the exercises related to while, but if you'd like to give it a try you may do so, see below. We will be doing one or two at the beginning of the next session.


Monday, September 6th

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
print "TADAM!"

Refresher exercises (while)

A.

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

Example program output (bold is user input):
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

B.

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

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

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)

C.

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 (bold is user input):
How many values to enter? 3
Enter value: 98
Enter value: 52
Enter value: 27
Average is: 59

Sample answer (A)

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

New concepts!

Lists, also known as arrays

  • A way of storing multiple values in a variable
  • "Addressing" a list begins from 0
crisps = ["Taytos", "Walkers", "King", "Pringles"]
adjectives = ["great", "awesome", "bad", "yucky"]

print crisps[0], "are", adjectives[0]
print crisps[1], "are", adjectives[1]
print crisps[2], "are", adjectives[2]
print crisps[3], "are", adjectives[3]

For loops

  • An efficient way of going through every element in a list or range
for i in range(0, 4):
    print crisps[i], "are", adjectives[i]
    
print

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

print

for x in crisps:
    print x
  • len(my_list) is a more efficient way of looping through the list, because even if you add or remove elements (new crisps brands) you only have to change your code in one place and it'll be automatically picked up
  • range(0, 4): the 1st number is inclusive, the 2nd is exclusive. range(0, 4) will give you the following list: [0, 1, 2, 3]

Crispy

We built on top of the first crisp example with several small exercises, until we arrived at something like the following:

crisps = ["Taytos", "Walkers", "King", "Pringles"]
adjectives = ["great", "awesome", "bad", "yucky", "meh"]
 
for c in crisps:
    print c, "are..."

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

    choice = raw_input()

    print c, "are", adjectives[int(choice)]
    print

What? Homework?! No!

There isn't actually any homework to do. If you'd like to practice a little though, you could get started on some of the 'for' exercises.


Monday, September 13th

Code reading

What does this do?

sentence = "Python is cool"

for letter in sentence:
    print letter

print sentence[1]

# That one is new. Have a guess?
print sentence.index('h')

A little detour: The fun world of string manipulation

sentence = "Python is cool"

print sentence.upper()
print sentence.lower()

More code reading

Using a boolean (True/False) as a "flag"

sentence = "Python is cool"

lower = False

for letter in sentence:
    if lower == True:
        print letter.lower()
        lower = False
    else:
        print letter.upper()
        lower = True

Exercises

A.

You have a list of numbers (you can either write the list yourself directly inside your program, or optionally ask the user for numbers). Print the largest number from the list.

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

Optionally: Make sure your program also displays the correct largest number when the list only contains negative numbers.

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

B.

You have a list of numbers. You can either write the list directly inside your program, or ask the user for a few numbers.

Add all the numbers in the list together, using a 'for' loop.

C.

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.

D.

Ask the user for a number between 1 and 12. Print the month associated with the number.

You probably should consider coding a list with all the months in the correct order, and use this to give the user an answer.

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

Optionally: Display an error message if the user enter an incorrect number (e.g. 0, 13, 24).

Sample answer (A)

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

Highlighted is the way of solving the "optional" part of the exercises: by initialising the variable 'largest' with an element from the array, you ensure the result will always be correct 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
    print

Sample answer (D)

months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

number = raw_input("Please enter a number between 1 and 12: ")
number = int(number)

if number > 0 and number < 13:
    print "Month is", months[number-1]
else:
    print "Invalid month number."

New concepts: File handling

We'll keep using the crisp base from last week. First, let's create a new Python program that will ask the user for crisp brands and populate a file based on what the user types in.

Writing a file
file = open('crisps.txt', 'w') # r, w, a

crisp = raw_input("Please enter a crisp brand (Press enter to end): ")

while crisp != "":
    file.write(crisp + "\n")
    crisp = raw_input("Please enter a crisp brand (Press enter to end): ")

file.close()
  • The 3 modes are 'r' (Read), 'w' (Write), 'a' (Append). Try with different mode to see the differences.
  • \n is an "escape character" that creates a new line. Try without it.
Reading a file - option 1

We only need to change the first 3 lines of last week's example.

f = open('crisps.txt', 'r')
crisps = f.readlines()
f.close()
adjectives = ["great", "awesome", "bad", "yucky", "meh"] for x in crisps:     print x.rstrip('\n'), "are..."     for i in range(0, len(adjectives)):         print i, "-", adjectives[i]     choice = raw_input()     print x.rstrip('\n'), "are", adjectives[int(choice)]     print
Reading a file - option 2
file = open('crisps.txt', 'r')

for line in file:
    print line.rstrip('\n') file.close()

'rstrip' stands for "stripping from the right" (see the string manipulation link from the beginning of the session). It will remove any of the characters between the parenthesis until it meets a different character, e.g.

sentence = "Python is cool"

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

We ended the evening by working on more of the "For" exercises from the beginning of the session.


Monday, September 20th

Code reading

What will be displayed on screen at line 12?

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

count = 0

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

print count

Exercises (file handling)

(Note: The difficulty of the exercises was too much of a leap compared to the previous weeks and we didn't achieve much. The easiest is C, try your teeth on it.)

Rot13 is a basic encryption mechanism that works by replacing a letter by the letter that follows it 13 letters later in the alphabet: so, 'a' becomes 'n', 'b' becomes 'o', 'c' becomes 'p' and so on. To decrypt, you shift every character the other way around.

For example, 'hello, world! ' would become ' uryyb, jbeyq! '

Tip: Remember, a string is like an array of characters, so you can work on each letter one by one.

A.

Ask the user for a string of text. Then, encrypt the string using the rot13 mechanism. Store the encrypted string in a file called 'crypto.txt'. Only worry about handling lower case strings for now.

Example program output (bold is user input):
Enter sentence to encrypt: i really really like cake

Content of file crypto.txt:
v ernyyl ernyyl yvxr pnxr

B.

Read in a file, the filename should be named crypto.txt and contain a encrypted piece of text. Decrypt it and display the decrypted result on the screen.

Contents of file crypto.txt:
trnal vf dhvgr n tbbq cebtenz

Example program output:
geany is quite a good program

(A and B)².

Adjust A and/or B, so that they handle both lower case and uppercase sentences correctly.

Example program output (bold is user input):
Enter sentence to encrypt: I really REALLY like cake
V ernyyl ERNYYL yvxr pnxr

Tip: To find out if a string is lowercase or uppercase, you can call islower() or isupper() on the variable, e.g. name.isupper(). It will return True or False.

C.

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:
1
2
3

and file2.txt contains:
2
3
4

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

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.

Sample answer (A)

As previously said, this was too long to be figured out during one session.

rotation = 13
alphabet = "abcdefghijklmnopqrstuvwxyz"

text = raw_input("Enter sentence to encrypt: ")
result = ''

for letter in text:
    if letter in alphabet:
        # Find index of current letter in the alphabet
        index = alphabet.index(letter)
        # Find new index
        new_index = index + rotation
        if new_index >= len(alphabet):
            new_index = new_index - len(alphabet) # Wrap around the alphabet
        result = result + alphabet[new_index]
    # If the letter is not in the alphabet, it's probably a space or punctuation symbol.
    # We'll leave it as it is (no encryption).
    else:
        result = result + letter

print result

f = open('crypto.txt', 'w')
f.write(result)
f.close()

Hints for (A and B)²

This question is about enabling the program to deal with lower and upper case sentences. Try the following to get a feel for the solution.

letter = "A"
letter == "A" # True
letter == "a" # False
letter.lower() == "a" # True

With this you can check whether any letter is in our alphabet variable, by comparing it while it's lowercase.

After that, for A, you could have something like this to make sure you're encrypting it with the proper case:

        if letter.isupper():
            result = result + alphabet[new_index].upper()
        else:
            result = result + alphabet[new_index]

Sample answer (C)

file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')

results = open('results.txt', 'w')

for line1 in file1:
    line2 = file2.readline()
    result = int(line1) + int(line2)
    results.write(str(result) + "\n")

file1.close()
file2.close()
results.close()

New concept: Functions

def multiply(number): 
    result = number * number 
    return result    
    
print multiply(2) 
print multiply(3) 
print multiply(4) 
print multiply(5)
  • Self-contained section of code that can be reused over and over
  • Between the parenthesis are the parameters -> variables that will contain the value you use to "call" the function
  • Must be defined before you use it
  • Content ignored until called (if you remove the 4 multiply statement at the end, nothing will happen when executing the file)

If you name your file "mycoolfunctions.py", you can import it and call any function in it like this:

import mycoolfunctions

print mycoolfunctions.multiply(768)

Short exercise

Reusing the code from the exercise from last week, write a small function that takes a number as a parameter, and prints the multiplication table for it from 2 to 9.

Short exercise: Sample answer

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

Feedback form

I asked if people would be kind enough to fill in the following form, and got some very useful feedback out of it. Thanks!

Overall impression:
       Meh        ∘    ∘    ∘    ∘    ∘     Good
Knowledge acquired:
    I didn't learn much     ∘    ∘    ∘    ∘    ∘     I learnt a lot

What did you expect when you signed up for the course?
Did the course match your expectations?
Was there anything missing you would have liked us to look at?
Best/most interesting thing:
Least interesting thing/thing that didn't quite work:
Any idea or suggestion to make the course better?
Three words to describe the course:
Additional comments, feedback, ASCII art: