Creating a calculator

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Fri Jul 1 02:42:50 EDT 2016


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

:)



More information about the Python-list mailing list