This is an example of using mod_python PSP.
1 <%
2 """
3 session.psp
4
5 A PSP Guessing Game using session variables, a form variable,
6 and an if statement containing an html block.
7 """
8
9 import random
10 buttonText = "Submit"
11 if 'answer' not in session or 'input' not in form:
12 session['answer'] = random.randint(1, 100) # create 'answer' session variable
13 session['guesses'] = 0 # create 'guesses' session variable
14 message = "Guess a Number Between 1 and 100"
15 else:
16 session['guesses'] += 1
17 guess = form['input'] # retrieve value of 'input' form variable
18 if int(guess) == int(session['answer']):
19 message = "Correct. It Took You %s Guesses." % session['guesses']
20 del session['guesses'] # remove the guesses session variable
21 del session['answer'] # remove the answer session variable
22 buttonText = "NEW GAME"
23 else:
24 if int(guess) < int(session['answer']):
25 message = "Your Guess Was Too Low. %s Guesses. Try Again." % (session['guesses'])
26 else:
27 message = "Your Guess Was Too High. %s Guesses. Try Again." % (session['guesses'])
28 message = message.replace("1 Guesses","1 Guess") # we don't want '1 Guesses'
29 # end if (PSP needs this comment to close the if statment because html follows)
30 %>
31 <html><head><title>PSP Guessing Game</title></head>
32 <body onload="document.getElementById('txtInput').focus();">
33 <h3><%= message %></h3>
34 <form name="form1" method="post" action="session.psp">
35 <%
36 if buttonText == "Submit":
37 %>
38 <input type="text" id="txtInput" name="input">
39 <%
40 # end if (PSP needs this comment to close the html block of the if statement)
41 %>
42 <input type="submit" name="Submit" value="<%= buttonText %>">
43 </form>
44 </body></html>
Notes
This page should be called session.psp or if changed be sure to modify the action="session.psp" from the html form accordingly.
This program uses two session variables 'answer' and 'guesses':
answer: stores a random number between 1 and 100
guesses: stores the number of times the user has guessed for the answer.
It uses one form variable 'input'. That is from the textbox on the html form.
Basically the program starts out by generating a random number and asking the user to guess it. Each time the user submits a guess the program checks if they have guessed correctly in which case it displays an appropriate message and allows the user to press the button to start a new game. If the user guesses incorrectly it displays '..Too High..' or '..Too Low..', shows the number of guesses so far, and asks the user to guess again.
In the original if statement it probably doesn't need the "or not form.has_key('input')". That was included just to show how to check for the existence of a form variable.