Loading presentation...

Present Remotely

Send the link below via email or IM


Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.


John's Python Stuff

This is a collection of resources I use in my teaching. It is not meant to be a presentation (how long would that take!). It also isn't designed to be used independently - just material I use in some of my classes.

John Grey

on 23 April 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of John's Python Stuff

6 Output The print statement is used to print things on the screen.
You can print as many things as you like. Put them in brackets with commas between.
The end= option sets what is added after a print statement - a new line by default. print ('Hello')
print ('number is', 42)
print (42*27)

print('John') Input/Output The input statement will take an input from the user and store it in a variable - in this case a variable called name. name=input('What is your name? ')
print ('Hello',name) Input GCSE Computing (project) (a) identify and use variables, operators, inputs, outputs and assignments

(b) understand and use the three basic programming constructs used to control the flow of a program: Sequence; Conditionals; Iteration

(c) understand and use suitable loops including count and condition controlled loops

(d) use different types of data including Boolean, String, Integer and Real appropriately in
solutions to problems

(e) understand and use basic string manipulation

(f) understand and use basic file handling operations: open, read, write and close

(g) define and use arrays as appropriate when solving problems. for loop This is used where you want to do something for each item in some sort of collection of things. Like letters in a word, items in a list or numbers in a range. x = 'John'
for letter in x:
print(letter) Loops - iteration This loop will keep going while some condition is true reply='z'

while reply != 'stop':
print '-------'
reply = input('your input? ')

print ('all finished') while loop Errors There are broadly three types of error that you can get in programs: syntax errors, run time errors and logic errors. Syntax Errors These are errors where your program doesn't follow the syntax, or grammar, of the programming language. For example, in Python the print statement is always followed by the thing(s) to print in brackets.

So writing print 'hello' in a program would give an error.

Python will highlight where it spots a syntax error (though this might be a little after the actual mistake in the program). Run Time Errors These errors occur where your program does follow the correct syntax, but you are trying to do something the language doesn't allow.

An example of this would be trying to divide a number by zero,

try entering: print(27/0)

This will probably give an error message like this:

Traceback (most recent call last):
File "", line 1, in
print (27/0)
ZeroDivisionError: division by zero

These error messages can get quite long but the important lines to focus on are the last three - the final line should say what the error was and the lines before this should say which line of the program caused the problem.

Here are some other lines that might cause errors:

What do you think the problems are with them - try them in python and see what the error messages say:

print (Hello)

print ('hello'+ 17)

answer=input('please enter your name ')
print ('Hello',name) Logic Errors In a way these are not errors at all - at least not as far as python is concerned. A logic error is an error where the program is running without giving an error, the problem is that it isn't doing what you expected or wanted it to do. A Calculator We could use Python to turn your computer into a very expensive calculator by writing a program to input two numbers and add them. first = input ('enter the first number')
second = input ('enter the second number')
print ('answer: ', first+second) You can use + - * and / for mathematical operations in python.
// also divides but in a different way.
+ and * can also work with strings. Here is a simple adding program: What is the error in this? Data that variables refer to can be of various types (amongst others) numeric and string data - numeric values can be either integer or floating point.

The problem here is that the input() function always returns a string, not a number. If we are to use the result of input() as a number we need to use a function, either int() or float() to produce an integer or floating point number from the string.

We can either use the function on the string variable:
first = int(first)

or we can use the function directly on the result of input:
first=int(input('enter the first number ')) Guessing Game We could make a simple guessing game where we try to guess a number and the computer indicates whether our guess is too high, low or is correct.
Enter the program below into a new window. here is a start to this target=5
guess = int(input('guess a number '))
if guess > target:
print ('too high') You could add extra lines to deal with the situation where the guess was too low or correct. Note that the sign for equal to is == as we use the = symbol on its own to assign variables.
An if statement takes the form if condition :
followed by one or more indented lines which are only executed if the condition is true Improving the game Using a random number to start It's not going to be very exciting if the target number is always 5 - better to get the computer to pick a random number. We can do this using a function called randint(n1,n2), which will give us a random number between n1 and n2.

randint() is defined in a separate module called the random module, which we need to import if we are to use any of its functions. from random import *

target = randint (1,100) Repeating until the answer is correct It would be good to repeat the guessing until the person got the answer right. We can do this with a while loop. This repeats a block of statements while a condition is true from random import *
while guess != target:
{input a guess}
{check if it is too high}
{check if it is too low}
print('well done') the bits in curly brackets are things we have already done.
There is still an error in this program - see if you can spot it. name = 'John'
for x in name:
count = count + 1
print('letter',count,'is',x) Random Sentences This is another program that uses the random module, in this case to pick random words to make a sentence. So that the sentences are not complete nonsense we can make sure the correct type of word (noun, verb and so on) appear in a sensible order. The program makes use of functions to return random words of the correct type. The main program uses these functions to get the words which it prints out. 'The' in the main program is in quotes so it is printed out as it is.

Each function makes use of a list - a list is a collection of things, in this case strings. Lists are enclosed in square brackets and the items in the list are separated by commas. The (I think badly named) choice() function is part of the random module and returns an item picked randomly from the list. import random

def noun():
return random.choice(nounlist)

def verb():
return random.choice(verblist)

# the main program
print ('The',noun(),verb()) These sentences are a bit limited - you could make things more interesting by adding additional words and adding and using additional functions for other parts of speech: adjectives, adverbs, prepositions and so on.

You could also change the main program to print out lots of random sentences each time you run the program. To repeat a block of statements a set number of times you can use a for loop like this:

for n in range(10):
print(.... http://docs.python.org/release/3.1.5/library/functions.html Variables in Python can refer to a number of different types of data (there are others but these are what we will need to start):

Strings: are any collection of characters. To refer to them literally you put them in quote marks.

Integer: are whole numbers - to refer to these you just write the number.

Floating point number: are numbers with a decimal part - written as an integer but with a decimal point.

Boolean: is a variable that can take (only) the values True or False (the capitals do matter).

Lists: can be of any of the above, these can be mixed and can include more lists. Represented as things in square brackets with commas between the items.

Assign a value to a variable with the = operator. So we can write things like:
still-awake = True
or cheeses = ['Cheddar','Gorgonzola','Red Leicester'] Variables A Scrabble Checker We could write a program to read a file of words and then to check if a particular word was in the file. You will need a text file of words saved in the same place as your python programs. aa aah aahed aahing aahs aal aalii aaliis aals aardvark aardvarks aardwolf aardwolves aargh aarrgh aarrghh aas aasvogel aasvogels ab aba abaca abacas abaci aback abacterial abacus abacuses abaft abaka abakas abalone abalones abamp abampere abamperes abamps abandon abandoned abandoner abandoners abandoning abandonment abandonments abandons abapical abas abase abased abasedly abasement abasements abaser abasers abases abash abashed abashes abashing abashment abashments abasia abasias abasing abatable abate abated abatement abatements abater abaters abates abating abatis abatises abator abators abattis abattises abattoir abattoirs abaxial abaxile abba abbacies abbacy abbas abbatial abbe abbes abbess abbesses abbey abbeys abbot abbotcies abbotcy abbots abbreviate abbreviated abbreviates abbreviating abbreviation abbreviations abbreviator abbreviators abdicable abdicate abdicated abdicates abdicating abdication abdications abdicator abdicators abdomen abdomens abdomina abdominal abdominally abduce abduced abducens abducent abducentes abduces abducing abduct abducted abducting abduction abductions abductor abductores abductors abducts abeam abecedarian abecedarians abed abele abeles abelia abelian abelias abelmosk abelmosks aberrance aberrances aberrancies aberrancy aberrant aberrantly the start of the file of 172804 words... The program to do this needs to open the file and read its contents into a variable:


The variable words will now refer to a string of the contents of the file - a list of words with spaces between each word.
If the words were in a list we could use the 'in' operator to check if a word was in the list.
The split method of a string will convert a string to a list:

wordlist=words.split(' ')

The string in the brackets indicates where to split the string - in this case at a space.
Now we can write code to input a string and check if it is in the list

x=input('enter a word> ')

if x in wordlist:
print('word ok') could you:

1 add line to give a response if the word was not ok - you can either use


or another if statement using not in .. as the condition

2 make the program run continuously until the user enters stop

3 write this as a function that returned True or False when a word was passed to it. Functions & Methods Searching the web Turtle Graphics Modules random the random module includes a range of functions to do with random numbers including:
choice() urllib.request the function urlopen() will open and allow you to read a web page sqlite3 provides a range of functions to access sqllite databases tkinter allows you to create elements of a GUI in Python turtle provides turtle graphics commands (needs tkinter as well) To import functions from a module you can use:

from modulename import * gets all the module functions from a module called modulename

from modulename import function,function ... to import specific functions

import modulename imports all the module functions but when you call them you need to use the syntax modulename.function() things like words or lists that have parts that you can iterate over are called iterators To make a loop carry on forever make the condition always true:

while 1=1:
commands to do forever
.... if - selection The if statement executes a block of statements if a condition is true.

Optionally you can use an else clause if condition:
things to do if condition true
things to do if condition not true
.... Conditions are anything that gives an answer True or False. For example:

if a > b:

if a == b: (means equal to)

if a != b: (not equal to) Strings are a sequence of any characters. To write a string literally, use quote marks. We can assign variables to refer to strings. name='John'
print(name) strings Here is a longer string which we will assign to a variable x
(text copied from the first paragraph at http://www.gutenberg.org/cache/epub/110/pg110.txt)

x = '''On an evening in the latter part of May a middle-aged man was walking
homeward from Shaston to the village of Marlott, in the adjoining
Vale of Blakemore, or Blackmoor. The pair of legs that carried him
were rickety, and there was a bias in his gait which inclined him
somewhat to the left of a straight line. He occasionally gave a
smart nod, as if in confirmation of some opinion, though he was not
thinking of anything in particular. An empty egg-basket was slung
upon his arm, the nap of his hat was ruffled, a patch being quite
worn away at its brim where his thumb came in taking it off.
Presently he was met by an elderly parson astride on a gray mare,
who, as he rode, hummed a wandering tune.''' We can refer to individual characters in a string using an index, or a group of characters with start and end indices: x='sunderland'
print(x[6:]) We can use a string's find method to find the position of a substring. x='sunderland'
print(x[p:]) What happens if the thing you are finding isn't in the string? Could we write code to:

print out the text between the words Shaston and Marlott?

In a way that would work with any text..

print the first sentence?

print the second sentence? - note that the find method can take a number to show what position to start the search. So x.find('a',10) would find the first 'a' after the tenth character. Python Functions: http://docs.python.org/release/3.1.5/tutorial/datastructures.html List methods: http://docs.python.org/release/3.2/library/stdtypes.html#string-methods String methods: This section is about writing a program to implement an internet search engine. The task will involve:
opening a page and collecting information on the page and all the links on the page
Storing the page address and information in a file
repeating the process for each of the links found on the page (and for links on those pages and so on)
writing a program to search the database returning all the pages with particular content abs() returns the absolute value of a number
float() returns a floating point number
input() returns keyboard input
int() returns an integer
len() returns the length of something
list() returns something as a list
open() returns an open file object
print() prints (and returns none)
range() returns a range for iteration
sorted() returns a sorted list
str() returns a string of something str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased.

str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.


Return a string which is the concatenation of the strings in the iterable. A TypeError will be raised if there are any non-string values in seq. The separator between elements is the string providing this method.


Return a copy of the string converted to lowercase.

str.replace(old, new)

Return a copy of the string with all occurrences of substring old replaced by new.


Return a list of the words in the string, using sep as the delimiter string.


Return a copy of the string with the leading and trailing characters removed.


Return a copy of the string converted to uppercase. list.append(x)
Add an item to the end of the list.

Extend the list by appending all the items in the given list.

list.insert(i, x)
Insert an item (x) at a given position(i).

Remove the first item from the list whose value is x.

Remove the item at the given position (i) in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.

Return the index in the list of the first item whose value is x.

Return the number of times x appears in the list.

Sort the items of the list.

Reverse the elements of the list. results=[]

for wordpair in lookuptable:
if wordpair[1]==w:

print(results) One of the modules that you can load into python provides logo style turtle graphics. Reference to turtle methods: http://docs.python.org/release/3.1.5/library/turtle.html Programs using turtle graphics need to import two modules - tkinter and turtle. You also need a line to set the mode of turtle graphics to 'logo'.

So turtle graphics programs always need to start with the lines: from tkinter import *
from turtle import *
mode('logo') Next we can create a turtle (in this case called brian) and then use its 'methods' to draw stuff. brian=Turtle()
... from tkinter import *
from turtle import *
from random import *


while count<1000:
count=count+1 Iteration (while loop) and the random module from tkinter import *
from turtle import *
from random import *


for l in lengths:
freda.rt(90) Iteration, for loop) from tkinter import *
from turtle import *
from random import *

def square(tu,size):
for x in range(4):


square(freda,100) Defining a function from tkinter import *
from turtle import *
from random import *


for l in range(100):
freda.rt(185) Iteration, for loop - using range() We might use turtle graphics to illustrate programming concepts Functions to convert data between types There are a series of functions to convert data to data of another type.

These are:

str() - to convert to a string
int() - to convert to an integer
float() - to convert to a floating point number
bool() - to convert to a boolean value
list() - to convert to a list

use these in statements like this:

s = str(100)
print (s)

print (s)

or just

So a string variable is created from 100 or, in the second case, the number referred to by the variable n

Not everything can be converted - this for example doesn't make much sense:

num=int(name) What happens if you try to convert these variables to the other types? i=100
l = ['cat','dog','mouse'] Changing the fourth example into a list and the final example into a string might have given unexpected results - there are other ways to do this ... My Bread Recipe STARTER:
dissolve yeast(5g)
flour (160g)
water (140g)
mix thoroughly
leave at room temp (12 hours)

add (mix(cracked wheat, jumbo oats, pinhead oatmeal), 100g)
add (water (100g))
leave (2 hours) BREAD:
add (Flour, 260g)
add (salt, 2g)
while not soft:
add tepid water

while not stretchy:

transfer dough to bowl
grease (polythene sheet, oil)
cover (bowl, polythene)
while not doubled in size:
leave at room temperature

fold in GRAINS
grease (loaf tin, butter)
with dough:
shape into loaf
roll on cracked wheat on worktop
put into loaf tin

cover (tin, polythene)
while not doubled in size:
leave at room temperature

bake in oven (170C, 40min)
turn out loaf
if you want a soft crust:
wrap loaf in clean tea towel

leave to cool on a wire rack. Anagram Finder Continuing with the Scrabble theme we could write a program to find anagrams.

One way to do this would be to make a huge table of words with two columns, one with the word itself and another column with the letters sorted into alphabetic order. cat act
dog dgo
mouse emosu
.. and so on To get the anagrams of a word, or just a collection of letters we could sort the letters into alphabetic order and then check if it appears in the second column (this might happen more than once). The matching first column entries will give the anagrams.

In python we could organise our table as a list of lists:

[[cat,act][dog,dgo][mouse,emosu] ... ] splitting a string to make a list Strings have a split method that splits the string up into lists. The method takes a parameter to show what character marks show where to split.

for example: s='cat,dog,mouse,elephant'
print (l) or s='cat dog mouse elephant'
l=s.split(' ')
print (l) a space combining the elements of a list into a string (the syntax of this is a bit odd) Strings have a method .join() that takes a list of strings as a parameter and joins them using the original string to separate the joined strings.

for example: l=['cat','dog','mouse']
print (s) l=['cat','dog','mouse']
s=' '.join(l)
print (s) l=['cat','dog','mouse']
print (s) first we open the word file, read the contents into a string called words and then split this into a list called wordlist. f=open('words.txt')
wordlist=words.split(' ') create an empty list that we will put out pairs of words and sorted words into lookuptable=[] for word in wordlist:



lookuptable.append(wordpair) for each word in the list of words:

sort the letters of the word into alphabetic order

create an empty list and then add the original word and the sorted word to it.

then add this pair of words into our main list of word pairs get a word from the user and sort its letters into alphabetic order w=input('> ')
w=''.join(sorted(w)) create an empty list for the results

go through the list of word pairs
if the second of a pair matched the sorted input word, add the first of the pair to the results list

and print the results list I suppose the program on the right would be better if there was a loop to allow the user to type in more words until entering something (perhaps q) to quit. The results could also be printed out in a better format. Design, code, test and evaluate a system to accept and test a password for certain characteristics.

It should be at least 6 and no more than 12 characters long
The system must indicate that the password has failed and why, asking the user to re-enter their choice until a successful password is entered.
A message to indicate that the password is acceptable must be displayed.
Password strength can be assessed against simple criteria to assess its suitability; for example a password system using only upper and lower case alphabetical characters and numeric characters could assess the password strength as:

WEAK if only one type used, e.g. all lower case or all numeric

MEDIUM if two types are used

STRONG if all three types are used.

For example

hilltop, 123471324, HAHGFD are all WEAK,
catman3 and 123456t are MEDIUM and

A message to indicate the password strength should be displayed after an acceptable password is chosen. Task 2 System password.
15 marks Task 3 High scores database.
15 marks Design, code and test a system to store and manage user names and their highest score.
The system must be able to:
create a file
add data to a file
locate data in the file by name and their highest score
delete an item and its associated data from the file
locate and update a high score for a user
The system need only cater for 10 items. Sample tasks OCR GCSE Getting a page from the web There is a module called urllib.request that provides a function urlopen() to get a page from the web.

Here is a program to get a web page and print it on the screen (well, the html at least): from urllib.request import urlopen


request = urlopen(address)


print (pagetext) Try this with some different pages (many pages are surprisingly long and complex).

What difference does it make including or missing out the .decode()

Have a look at what is printed out for some different pages. What could you collect if we wanted to get some words from the page to add to a database to search for web pages? Getting information from the page To build a database that we can search we need to store the addresses of web pages and some of the contents of the pages.
Most pages will have a title and many will have description and keywords sections designed for web crawlers.

Have a look at my favourite photographic suppliers at http://www.silverprint.co.uk

When we download a page we could try to collect this information.
We can use the find() method to do this.

Here is a piece of code to create a string variable content and add the text of the title to it. content=""

if start > 0:
content=content+stuff We could write this as a function (perhaps called pageinfo) so that in the main program we could just have a line like:


Where pagetext is all the text in the page and content is the bit we have collected from it.

Here is a function ... def pageinfo(pagetext):


if start > 0:

return content It would be good to add to this to pick up the description and keywords section as well. Functions take the form:


for example:

print(n) Methods are part of the definition of an object and take the form:


for example:


In the case of lists there might not be a separate result - the object itself is changed. depending on the function or method there might be 0 or more than 1 input Installing and Running Python You can download python from:
There are two main versions of Python, versions 2 and 3. We will be using Versions 3 which is currently (as I write this) up to version 3.2.3

You should find the Windows installer creates start menu entries for:

Python 3.2 >
IDLE (Python GUI)
Python (command line) When python starts you should get a window that looks something like this (this window is called the 'Python Shell) Python 3.2.2 (default, Sep 5 2011, 22:09:30)
[GCC 4.6.1] on linux2
Type "copyright", "credits" or "license()" for more information.
==== No Subprocess ====
>>> The prompt >>> indicates that the system is waiting for you to type something in.

If you type an expression - a number, word (in quotes) of some sort of sum, then python should evaluate it and print it on the screen.

Or you could enter a python statement like:

print ('hello') To enter a program of a series of commands select:
File > New Window

from the menu bar and then enter your program.

To run the program select
Run > Run Module

from the menu bar. You will be prompted to save your Python program before it will run. To start with it might be easiest to save it on the desktop - when you enter the file name use the extension .py Try entering these into the python shell - what do they do?
>>> 27
>>> a
>>> a=27
>>> a
>>> b=4
>>> b+a
>>> b/a
>>> 'Hello'
>>> print('hello')
>>> b='hello'
>>> b+b
>>> b*5
>>> b.upper() lists As the name suggests, lists are lists of things like strings, integers or other lists. Lists are shown literally in square brackets, with commas between the items in the list.

You can refer to items in a list using indices in the same way as with strings. What would these print statements produce? mylist=[101,'cat','mouse',['Sunderland',1],True]

print (mylist[0])
print (mylist[2])
print (mylist[3])
print (mylist[4])
print (mylist[3][0])
print (mylist[1][2])
print (mylist[3][0][1])
print (list (mylist[3][0])) Unlike strings, you can change individual elements in a list. a=['cat','dog','mouse']
print (a)
print (a) Getting the links in a page We can find links in a page in the same sort of way. What would we search for to find the (start of the) first link in a page? And the end of the link?
There will probably be a lot of links on a page. Later we will want to download and search the pages these links go to. So it might be easiest to keep a list of links, rather than putting them all into a string as we did with the content of the page.
Our function (we might call it getlinks) to get the links would need to:

make an empty list to contain the links
set a variable upto to 0
while there are more links in the page:
find the first link after position upto
add the link to the list of links
set the variable upto to the end of the link

return the list of links we could test this function with a main program like this: from urllib.request import urlopen


request = urlopen(address)


print (getlinks(pagetext)) - don't call your program by the same name as a module you might use! Putting the web crawler together Our web crawler program will need to:

create a list of pages to be crawled (initially containing just the url of a start page)
get the first page in the list to be crawled
get the contents
store the url and the contents so they can be searched later
get all the links on the page
add them to the pages to be crawled list
(I suppose we don't need to save the same page twice) If we are going to use a separate program to search our database of pages we are going to have to save the database in some way.

Two possibilities for this are to:

store the data in a list in the program and then write this to a file on disc. We would read the file back into a list in the program to do the searching;

or we could use a module for Python that allows us to create and use an SQL database. The searching program would access the same database. download the file from http://red2.sunderland.ac.uk/py/ SQLite Reference SQLite is a cut-down version of the SQL language designed to be incorporated in other systems. It is included in Python and can be accessed by importing the sqlite module.
Whereas SQL works as a client server application, SQLite is self-contained and saves all the data in a particular database in a normal file. There are specific python commands to create or connect to a database. Once you have done this you can use python to execute SQLite statements. Here are a few examples:

CREATE TABLE phonebook (surname TEXT,forename TEXT, phonenumber TEXT)
CREATE TABLE IF NOT EXISTS phonebook (surname TEXT,forename TEXT, phonenumber TEXT)
creates a table

DROP TABLE phonebook
deletes a table - no warnings, wastebins or undos - so be careful!

INSERT INTO phonebook (surname,forename,phonenumber) VALUES ("Grey","John","2383")
adds a record to the table

SELECT * FROM phonebook
returns all the fields for all the records in the table

SELECT forename,phonenumber FROM phonebook
returns particular fields for all the records

SELECT forename,phonenumber FROM phonebook WHERE surname="Grey"
returns the same data for records matching the criteria

SQLite stores information about tables in a special table called 'sqlite_master'. To get a list of tables in the current database you can use:

SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;
to get details of a table use:
There is full documentation at the SQLite web site:

http://www.sqlite.org/lang.html Setting up our Database We can use SQLite to set up a database for our links:

We need to import the sqlite module at the start of the program and connect to the database:

import sqlite3
dbase = sqlite3.connect('sql.db')

if it doesn't exist we will need to create a table for our data:

command='CREATE TABLE IF NOT EXISTS pages (info TEXT,address TEXT)'

Now we can add data to the database. Suppose we have the address of the page and the content we have collected in the variables url and content:

command='insert into pages (info,address) values (" '+url+' "," '+content+' ") '
dbase.commit() Searching the Database We could write a separate program to search our database.

We would then open the database:

import sqlite3
dbase = sqlite3.connect('sql.db')

Then allow the user to type in a word to search for (say into a variable called term)

term=input('enter a search term> ')

and search for the word in the content field of the database, returning matching URLs:

command='select url from pages where "%'+term+'%" like info'

for row in c:
print ( c[row] ) 1 Python There is a small set of linked web pages to practice on at:
http://red2.sunderland.ac.uk/py/ne Hangman def pickword():
# returns a phrase for the game
return 'norwegian blue parrot'

def makeblankword(someword):
# creates a blanked out word with dashes and spaces
# in place of letters and spaces
blankword = ''
for n in someword:
if n==' ':
blankword=blankword+' '
return blankword


print(' ',wordsofar)
while wordsofar!=target:
letter=input('input a letter ')
for n in range(len(target)):
if letter==target[n]:
newwordsofar = newwordsofar+letter # or +target[n]
newwordsofar = newwordsofar+wordsofar[n]

print(' ',wordsofar)
print() This program includes two functions, one to come up with a word for the game, the second to create a blanked out word.

Could you:

Make the game a bit more interesting by picking the phrase from a list of possibilities.

Print a message to say well done when the person has won the game.

Keep the score and perhaps give the player a limited number of goes.

(Later you might try keeping a best scores table that would record names and scores between games.) http://xkcd.com/353/ A phone number book (practicing the use of lists and files) One way to create a phone book is to store the book as a list of items where each item in the list is itself a list of name and number. We could then write functions to do things like add a name, search for a name and so on. [['John','515 2383'],['Reception','515 2395'], ['Switchboard','515 2000'] .... ] We will need to allow the user to do a number of different tasks - so we could use a menu system like this: A Menu System def getmenuchoice():
print('1\tadd an entry')
print('2\tprint all numbers')
print('3\tdelete a number')
print('4\tfind a number')

userchoice=input('enter number> ')

#main program

if ch=='1':
print('you chose to add an entry')

if ch=='2':
print('you chose to print all the numbers')

... and so on Obviously, in the statements underneath the if statements, we will need to actually do the relevant tasks, rather than just printing what it is.

It would also be good to deal with other inappropriate inputs. More of the main program We will need some other things in our main program. We are going to store our names and numbers in a list, so to start with we need an empty list to hold the directory - which could be called directory. #main program

directory = [ ]

ch=getmenuchoice( )
if ch=='1':
print('you chose to add an entry')

if ch=='2':
print('you chose to print all the numbers') But, we don't want to re-run the program every time we need to add a new name - apart from anything else this would set the directory back to an empty list, losing anything we had entered.

We need a loop so that we can repeatedly carry out new actions. #main program

directory = [ ]

continue = True
while continue:

ch=getmenuchoice( )
if ch=='1':
print('you chose to add an entry')

if ch=='2':
print('you chose to print all the numbers') Adding a new name and phone number \t means inset a tab character To add a new phone number we can modify our choice 1 to look like this: ch=getmenuchoice( )
if ch=='1':
e=inputentry( )
print (e, 'added to directory') This code makes use of a function which gets the name and phone number from the user and returns these in a list to the main program.

We need to write this function. def inputentry( ):
entry=[ ]
n=input('name> ')
p=input('phone> ')
return entry Printing out the whole directory To print out the whole directory we just need to go through everything in directory, printing it. We could just do this in the main program under choice 2: if ch=='2':
for entry in directory:
print(entry) You might be able print this out a bit more tidily. Entry is made up of two parts, entry[0], the name and entry[1] the number. Looking up a number This is a bit more complicated than printing all the names and numbers so we could write a separate function to do this. The function will need the directory list as an input and should return a list of any matching names and numbers.

So the main program will look like this: if ch=='3':
entries = getmatches(directory)
print(entries) This uses a function called getmatches - we need to write this now. getmatches will have one input (directory) and will return one output (the list of matches).

Above we are just printing the returned list - it would be better to print it more tidily and perhaps give a message if there were no matches. directory list list of
matches getmatches() The getmatches() function will need to get a name from the user and then go through the list that was passed to it finding any matches and storing these in the list to pass back.

The function will start with the name and a variable to represent the list passed to the function:

def getmatches(dirlist):

next we need to get a name for the user

name=input('enter name ')

next we go through the list checking whether name appears in the first element of each of the items in name. If it does, we can add the item from the directory list into a results list (which starts empty)

results=[ ]
for e in dirlist:
if name in e[0]:

and finally return the our results list to the main program

return results gets an input from the user we could have said
if name == e[0]
but then it would have had to match the whole name Using a file to store the data A serious problem with the phone book so far is that the data isn't persistent - every time you run the program you start with a new empty list. We need a way to save and load the data to and from a file on disc.
To save and load data we will need two new items on our menu and corresponding 'if' sections in the main program. The code following the if statements probably only needs to be a single line to call a function, one to which we will pass the director list to be saved, the other to assign a loaded list to the directory variable. Function to save the data Function to load the data if ch=='4':

if ch=='5':
directory=loaddata() To save the data we need to open a file in write 'w' mode and then go through the list of names and numbers writing them to the file - this code puts each entry on a new line with commas between the names and the numbers. def savedata(dirlist):


for n in dirlist:

f.close() def loaddata():



for n in f:

return (dirlist) This function creates an empty list and then opens the file for reading. The for statement then loops through each line of the file - for each line it:
assigns a variable (entry) to the line, with the final return stripped off (strip())
it then splits the line, which is read as a single string, into a list using the comma as the place to divide the string *
it then adds the list to the list 'dirlist'

when all the lines have been read the resulting list is returned. * - it changes, for example
'john,12324' to ['john','1234'] - there are lots of ways in which this program could be improved! sum and average functions You get these with Excel, but not as standard with python

- but we can make them ... def sum (listofnumbers):
for n in listofnumbers:
return total

def mean (lnos):
return t/l

a = [1,2,3,4,5,6,7]

print (sum(a))
print (mean(a)) 2 3 4 5 Scrabble 7 8 2012 9 Phone Book Searching the Web Hangman (or we could write this as a function) from tkinter import *
from turtle import *
from random import *


def outofbounds(t):
return False


for n in range (10):

while True:
for n in tlist:
if outofbounds(n):
n.pd() A list of Turtles - a more complex example where we are working with a list of 10 turtles What should outofbounds() do?
Can you make it work? from tkinter import *
from turtle import *
from random import *


def outofbounds(t):
#this could be improved!
if t.xcor()>600:
if t.xcor()<-600:
if t.ycor()>400:
if t.ycor()<-400:
return result



for n in range (10):

while True:
for n in tlist:
if outofbounds(n):
n.pd() def getnextlink(pagetext,upto):
start=pagetext.find('<a href="',upto)
if start > -1:
return link,upto,found

def getalllinks(pagetext):
while found:
return links from urllib.request import urlopen

request = urlopen(address)

newlinks= getalllinks(pagetext)

for l in newlinks:
print (l) Setting up a Web Server This might be better done by using recursion. from http.server import HTTPServer, CGIHTTPRequestHandler

print( 'starting the server on port', str(httpd.server_port))
httpd.serve_forever() There is a python module that creates and runs a web server. Here is the code to do this - it is probably best to put this into a separate folder. When you run the program you will be able to go to your web server by running Firefox and going to the address 'localhost'. This might run more reliably if run from the command prompt rather than from IDLE. You could create and add some web pages to the folder. If you want one to load automatically, call it index.html The Python web server We can make web pages interactive by creating python programs that produce the pages. To do this we need to create a separate folder in the folder where out web server is located called 'cgi-bin'. This is where we put python programs to generate web pages. Sending the output of a Python Program to your web server Here is an example of a program to generate a (very simple) web page. The print statements instead of printing on the screen generate the html of the web page #!/usr/bin/python3

import cgi
print('Content-type: text/html \n\n')

print('<hr>Hello, this has been printed from python<hr>') to access this you need to create a web page in the main folder that links to this file - like this. <p>
This is a normal web page
link to <a href="cgi-bin/test.py">test</a>
<hr> save this as test.py in the cgi-bin folder save this as test.html in the main web site folder Desktop server gci-bin server.py
*.html test.py In the last box we got python to output to a web page (we could of course have done something more complicated than just printing hello).
To input to a python CGI program we need to use a web page that includes a form.
Here is a very simple example: Input and Output through Web Pages This is an example of a program to generate a (very simple) web page. The print statements instead of printing on the screen generate the html of the web page. <html>
<form name="inputname" action="cgi-bin/hello.py" method="post">
What's your name? <input type="text" name="usersname" />
<input type="submit" value="Submit" />
</html> This page include a form which allows the user to enter a single field - called username. This will then be passed to a python file in the cgi-bin directory called hello.py #!/usr/bin/python3

import cgi
#import cgitb

pagedata = cgi.FieldStorage()
name = pagedata['usersname'].value

print('Content-type: text/html \n\n')
print('<hr><h1>Hello',name,'</h1><hr>') save this as name.html in the web server folder save this as hello.py in the cgi-bin folder Here is the hello.py file: john.grey@sunderland.ac.uk the list.pop() method will be useful here join two lists with the + operator from tkinter import *
from turtle import *


def tree (n):
if n<5 :
tree (n/2)
tree (n/2)

tree(200) trees from tkinter import *
from turtle import *


def tree (tur,n):
if n<5:
tree (tur,n/2)
tree (tur,n/2)


tree(fred,200) from tkinter import *
from turtle import *


class TreeTurtle(Turtle):
def __init__(self):
super( TreeTurtle, self).__init__()

def tree (self,n):
if n<5 :
self.tree (n/2)
self.tree (n/2)


fred.tree(200) from tkinter import *
from turtle import *
class TreeTurtle(Turtle):
def __init__(self):
super( TreeTurtle, self).__init__()

def tree (self,n):
if n<5 :
self.tree (n/2)
self.tree (n/2)

freda.tree(200) from urllib.request import urlopen


request = urlopen(address)


print (words[0:500])
# best not to try to print them all if we make use of the urllib module we can use a function that reads a resource on the web straight into a variable def forecast():
from urllib.request import urlopen
request = urlopen(address)
return fc

print(forecast()) a function to get the weather from the web from tkinter import *
from turtle import *
from random import *

class DTurtle(Turtle):
# a turtle with fd() redefined
def __init__(self):
super( DTurtle, self).__init__()
def fd (self,n):
while self.distance(target)>5:

ht() #hide the default turtle


for n in range(4):
fred.rt(90) development area from tkinter import *
from turtle import *


def square (n):
for i in range(4):

square(200) Squares from tkinter import *
from turtle import *


def square (tur,n):
for i in range(4):


square(fred,200) from tkinter import *
from turtle import *


class SqTurtle(Turtle):
def __init__(self):
super( SqTurtle, self).__init__()

def square (self,n):
for i in range(4):


fred.square(200) from tkinter import *
from turtle import *
from random import *

class DTurtle(Turtle):
# a turtle with fd() redefined
def __init__(self):
super( DTurtle, self).__init__()
def fd (self,n):
while self.distance(target)>5:

ht() #hide the default turtle


for n in range(4):
fred.rt(90) john.grey@sunderland.ac.uk Functions to match partial words def match(pword,dword):
for n in pword:
if n!= '?':
if n!=dword[index]:
return matched

def match2(pword,dword):
for n in pword:
if n== '?':
pass # means do nothing
if n!=dword[index]:
return matched

print (match2('he?l?','hello')) or Cheating at Crosswords def match(pword,dword):
for n in pword:
if n!= '?':
if n!=dword[index]:
return matched

def getwords():
from urllib.request import urlopen
request = urlopen(address)
wordlist=words.split(' ')
return wordlist

word = x
while word!='q':
word=input('word or q> ')
for n in wordlist:
if len(n)==len(word):
if match(word,n):
Full transcript