Creating a calculator

Christopher Reimer christopher_reimer at icloud.com
Fri Jul 1 08:25:58 EDT 2016


> On Jun 30, 2016, at 11:42 PM, Jussi Piitulainen <jussi.piitulainen at helsinki.fi> wrote:
> 
> DFS writes:
> 
>> Here's a related program that doesn't require you to tell it what type
>> of operation to perform.  Just enter 'num1 operator num2' and hit
>> Enter, and it will parse the entry and do the math.
>> 
>> -----------------------------------------------
>> ui=raw_input('Enter calculation to perform: ')
>> n1=float(ui.split(' ')[0])
>> op=ui.split(' ')[1]
>> n2=float(ui.split(' ')[2])
>> if op=='+':c=n1+n2
>> if op=='-':c=n1-n2
>> if op=='*':c=n1*n2
>> if op=='/':c=n1/n2
>> print(ui+' = '+str(c))
>> -----------------------------------------------
> 
> I use multiple assignment a lot, like this:
> 
>    n1, op, n2 = ui.split()
> 
> It's not only compact, it also crashes if there are more elements than
> expected, and I want it to crash when that happens. Or rather, I prefer
> a crash to silence when input is bad.
> 
> For the calculator, it may be better to split on any whitespace and
> discard empty strings, which is what ui.split() does. Splitting on a
> single space seems unnecessarily strict in a calculator (whereas
> splitting on a single tab is what I very much do in my work - the data
> formats are such).
> 
> I think multiple assignment is good even for a beginner. Perhaps do it a
> second time straight away:
> 
>    n1, op, n2 = ui.split()
>    n1, n2 = float(n1), float(n2)
> 
> But it's only with the split where it really pays.
> 
>    n1, op, n2 = ui.split()
>    n1 = float(n1)
>    n2 = float(n2)
> 
> The latter might be even preferable. Hm.
> 
>    n1, n2 = map(float, (n1, n2))
> 
> :)

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. 

Chris R.


More information about the Python-list mailing list