[Tutor] CGI Calculator

Darren Williams D3IBZ at hotmail.com
Mon Jul 16 18:38:29 CEST 2007

Hi all,

I am a Python convert coming from a JavaScript background (as you can probably tell) and am currently writing my first application using Python which will be a calculator for an online game I used to play (thought it would be a decent first project) but am not sure on the syntax for referencing an HTML form input field, I tried this (which returns an error) - 

XHTML form - 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <title>DopeWars Junkie Calculator</title>
    <form method="post" action="http://newspyn.com/cgi-bin/JunkieCalc.py">
        <p><b>Coat Size:</b>&#32;<input type="text" name="coatSize">
        <p><b>Used Pockets:</b>&#32;<input type="text" name="usedPockets">
        <p><b>Lab Space:</b>&#32;<input type="text" name="labSpace">
        <p><b>Total Junkies:</b>&#32;<input type="text" name="totalJunkies">
        <p><b>Dealer Visits Remaining:</b>&#32;<input type="text" name="DVR">
        <p><input type="submit" value="Submit">

junkieCalc.py - 

#!/usr/bin/env python

import cgi

def main():
    print "Content-type: text/html\n"
    form = cgi.FieldStorage()
    if form.has_key("coatSize") and form.has_key("usedPockets") and form.has_key("labSpace") and form.has_key("totalJunkies") and form.has_key("DVR") and form["coatSize"].value != "" and form["usedPockets"].value != "" and form["labSpace"].value != "" and form["totalJunkies"].value != "" and form["DVR"].value != "":
        Tokens = 0
    while usedPockets > (totalJunkies - labSpace) * 17:
        Tokens = Tokens + 1
        usedPockets = (usedPockets - totalJunkies + labSpace) * 17
        totalJunkies = totalJunkies + 1
        print "Tokens"
        print "Try again"


This is the error i'm getting - 

Traceback (most recent call last): File "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line 23, in ? main() File "D:\inetpub\vhosts\newspyn.com\cgi-bin\JunkieCalc.py", line 10, in main while usedPockets > (totalJunkies - labSpace) * 17: UnboundLocalError: local variable 'usedPockets' referenced before assignment

Thanks in advance for any help :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070716/990edd43/attachment.html 

More information about the Tutor mailing list