Creating a calculator

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Fri Jul 1 09:35:41 EDT 2016


Christopher Reimer writes:

>> On Jul 1, 2016, at 5:46 AM, Jussi Piitulainen 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.

You get to decide!

(But if you split on whitespace as I suggested, there won't be any extra
spaces in the line number or keyword. While if you split on every single
space, the first and second component of the split may not even contain
the intended line number and keyword. Try it. Then do what you like.)

> 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.

C syntax is not line-oriented anyway. It's semicolon-oriented.

Good luck with your BASIC interpreter. (No sarcasm or anything like
that. I think it's a nice project.)



More information about the Python-list mailing list