[Tutor] iterators

Danny Yoo dyoo at hashcollision.org
Mon Jul 4 17:56:42 EDT 2016


On Mon, Jul 4, 2016 at 1:38 PM, Colby Christensen
<colbychristensen at hotmail.com> wrote:
> I'm sure this is something simple but I'm missing it.
> When I check the statement with two values, the if statement works. However, for the statement with one value I get an error.
> keycode = event.GetKeyCode()
> if keycode in (13, 370):
>     self.enter()
> elif keycode in (43, 388):
>     self.add()
> elif keycode in (45, 390):
>     self.sub()
> elif keycode in (42, 387):
>     self.mult()
> elif keycode in (47, 392):
>     self.div()
> elif keycode in (27):
>     self.clear_all()
> elif keycode in (67, 99):
>     self.display.SetValue('')
> else:
>     event.Skip()


As Alan mentions, you've hit an "edge case" in Python's grammar.
Specifically, the grammar for defining tuples has a somewhat strange
edge case with regards to the 1-tuple.

    https://wiki.python.org/moin/TupleSyntax

where we need to add a trailing comma, even though it looks funky.


Why do we need it?  The reason that this edge case exists is to
disambiguate the 1-tuple from a different part of Python's grammar
involving parenthesized expressions.  Parentheses are used to enforce
a particular grouping of operations.

As an example, the math expression,

    y * (x + z)

uses parentheses to group the "x + z" part.  If we didn't use parens
there, it's harder to express the idea of adding 'x' and 'z' together
before multiplying by 'y', because multiplication "binds" more
strongly than addition, according to the grammatical rules.


So the extra trailing comma in a 1-tuple parenthesized expression is
just there to make it different looking, to disambiguate it from the
use of parentheses for expression grouping.


More information about the Tutor mailing list