Creating a calculator

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Fri Jul 1 08:46:03 EDT 2016


Christopher Reimer writes:

> For my BASIC interpreter, each line of BASIC is broken this way into
> tokens.
>
> line_number, keyword, *expression = line.split(' ', 2)
>
> For a line like 10 PRINT "HELLO, WORLD!", this works as expected.
>
> For a line like 20 END, which doesn't have a third element for
> expression, an empty list is assigned.
>
> By using * to unpack the split line, my program no longer crashes and
> no try/except block is needed to work around the crash. A later line
> of code will test the expression, ignore if empty or run regex if
> full.

Yes.

Consider line.split(None, 2) or line.split(maxsplit=2). You may still
need to strip the third component, but at least it will *be* the third
component even if the user happens to type extra spaces like this:

10   PRINT  "Hello, world."

And you won't get a spurious third component if the user types this:

20 END   

(There's trailing spaces.)



More information about the Python-list mailing list