Creating a calculator

Christopher Reimer christopher_reimer at icloud.com
Fri Jul 1 09:19:00 EDT 2016


> On Jul 1, 2016, at 5:46 AM, Jussi Piitulainen <jussi.piitulainen at helsinki.fi> wrote:
> 
> 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.)

This is a BASIC interpreter. Any extra spaces for line_number or keyword will raise an incomprehensible syntax error, as the line number must convert to an integer and the keyword much match the KEYWORDS list. As for trailing spaces for expression, regex will keep them whole if enclosed in double quotes or convert them to a list element. Depending on the keyword grammar, extra spaces are likely to be ignored.

A C interpreter would be more difficult as the same line of code could be written several different ways and be valid.

FILE *source
FILE * source
FILE* source
FILE*source

The first line is how I normally see this statement written. The last line I found in a 1991 book with a strange dialect of C that I've never seen before and doesn't always compile correctly without modification. Writing a C interpreter is not on my to do list. 

Chris R.


More information about the Python-list mailing list