[Tutor] CGI Calculator

Eric Brunson brunson at brunson.com
Mon Jul 16 20:48:24 CEST 2007


Darren Williams wrote:
> Now another problem - the script is just printing the word 'Tokens' 
> over and over again, it's supposed to work like this (JavaScript 
> version made by me) - http://nazkyn.brinkster.net/1.8.html
>
> Thanks in advance for any help :)

It's doing exactly what you've told it to do:

   while usedPockets > totalJunkies - labSpace * 17:
       Tokens = Tokens + 1
       usedPockets = (usedPockets - totalJunkies + labSpace) * 17
       totalJunkies = totalJunkies + 1
       print "Tokens"

The print statement is inside the while loop and you've quoted the work 
"Tokens" so it's printing the string rather than the variable.

How about grabbing a short tutorial on Python and reading through it to 
better understand the differences between Python and Javascript.  If 
you're an experienced JS programmer it shouldn't take very long.

This is probably closer is what I infer you're looking for:

   while usedPockets > totalJunkies - labSpace * 17:
       Tokens = Tokens + 1
       usedPockets = (usedPockets - totalJunkies + labSpace) * 17
       totalJunkies = totalJunkies + 1
   print "Tokens: %s" % Tokens

e.

>
> ----- Original Message ----- From: "Eric Brunson" <brunson at brunson.com>
> To: "Darren Williams" <D3IBZ at hotmail.com>
> Cc: <tutor at python.org>
> Sent: Monday, July 16, 2007 2:01 PM
> Subject: Re: [Tutor] CGI Calculator
>
>
>> Darren Williams wrote:
>>> Ok, now i've modified my script but am getting another error, i've 
>>> commented a few useless (hopefully) lines out -
>>>
>>> #!/usr/bin/env python
>>>
>>> import cgitb; cgitb.enable()
>>> import cgi
>>>
>>>
>> [snip]
>>>         17     while usedPockets > totalJunkies - labSpace * 17:
>>>
>>>         18         Tokens = Tokens + 1
>>>
>>>         19         usedPockets = (usedPockets - totalJunkies + 
>>> labSpace) * 17
>>>
>>>      usedPockets = '192000', totalJunkies = '200', labSpace = '0'
>>>
>>> TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>      args = ("unsupported operand type(s) for -: 'str' and 'str'",)
>>>
>>
>> What does "dog" - "cat" mean?  Similarly, what does "100" - "12" 
>> mean? It's not the same in Python as 100 - 12, because those are 
>> numbers, "100" and "12" are strings which happen to represent numbers.
>>
>> You need to coerce those strings into integers, maybe like this:
>>
>> usedPockets = int(form["usedPockets"].value)
>>
>> When you do that, you'll probably need to catch any exception that 
>> could occur if the string can't be converted.
>>
>>>
>>>
>>> It's confused me - it says I can't subtract a string from a string 
>>> but then gives the value's of the variables (that I randomly entered 
>>> into the form) at the bottom - usedPockets = '192000', totalJunkies 
>>> = '200', labSpace = '0'
>>>
>>
>>
>



More information about the Tutor mailing list