[Tutor] If/else in Python 2.6.5 vs. Python 2.4.3
Wayne Werner
waynejwerner at gmail.com
Mon Oct 11 19:46:10 CEST 2010
On Mon, Oct 11, 2010 at 12:10 PM, <aeneas24 at priest.com> wrote:
> <snip>
>
> rgenre = re.split(r';', rf.info["genre"] if "genre" in rf.info else []
>
> I get a syntax error at "if" in 2.4.3.
>
That's because you're using the ternary operator that was not available in
2.4: http://www.python.org/dev/peps/pep-0308/
>
> I tried doing the following but it doesn't work (I don't understand why).
>
> if "genre" in rf.info:
> rgenre = re.split(r';', rf.info["genre"])
> else:
> []
>
>
> And I tried this, too:
>
>
> if "genre" in rf.info:
> rgenre = re.split(r';', rf.info["genre"])
> if "genre" not in rf.info:
> []
>
> Both of these cause problems later on in the program, specifically
> "UnboundLocalError: local variable 'rgenre' referenced before assignment",
> about this line in the code (where each of these is one of the 30 possible
> genres):
>
The problem isn't with your logic expression - it's because on the else case
you never assign anything to rgenre, you simply state 'empty list' - not
'set rgenre to be an empty list'.
if 'genre' in rf.info:
rgenre = re.split(r';', rf.info['genre'])
else:
rgenre = []
will work on all(?) versions of python - and 2.4 certainly.
HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101011/04e457c7/attachment.html>
More information about the Tutor
mailing list