Nested if's

Thomas Wouters thomas at xs4all.nl
Fri Oct 15 11:48:55 EDT 1999


On Fri, Oct 15, 1999 at 03:20:51PM +0000, GeoJempty wrote:

> Enough for intros.  I'm having a problem nesting if statements.  I'm defining a
> function, and my syntax checks fine, until I try the following:

> if digit > 0:
>   if digit = 5:
>     variable = variable + whatever

> In the context of a CGI program this causes an Internal server error,

The problem is not the nesting, the problem is that you aren't testing for
equality, you're assigning. 'digit = 5' assigns 5 to 'digit'. What you want
is 'digit == 5' which returns 1 if digit is 5, and 0 otherwise (*)

But in python, you can't assign inside an if statement (or inside any
other statements, for that matter.) So Python throws an exception, which
terminates your python script, and leaves the webserver hanging there.
(hence the error 500.)

(You should thank Guido though, in other languages, this would have run just
fine, with the exception that whatever 'digit' really was, as long as it was
larger than 0, it would end up being 5.)

What you are looking for is:

if digit > 0:
  if digit == 5:
    variable = variable + whatever

Also, CGI isn't the right runtime enviroment for these things, mostly
because the webserver will give you an Error 500 without much other info the
moment it sees an error. And printing out errormessages before the standard
'Content-Type: text/plain' is an error. It's probably best to try and run
such scripts at the command line prompt, or if that's not possible, put this
in front of the CGI scripts you're trying to debug:

print "Content-Type: text/plain\n"
import sys
sys.stderr = sys.stdout

This way, error reports are printed to normal standard output (which the
webserver sends to your browser) instead of
standard error output, which the webserver usually puts in the error logfile
along with a timestamp.

webservers-errorhandling-suck-ly y'rs, Thomas.

(*) Yes, I know this isn't really correct. It doesn't really test wether
'digit' is 5, it tests wether 'digit's 'value' is equal to '5', using a
__cmp__ method on 'digit' or on '5' if there are any. Just like 'digit = 5'
doesn't really assign the value of '5' to 'digit', just makes 'digit' a
pointer to the same object as '5' is. Semantics, semantics ;)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list