[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

I need help with making my claculator

On Sat, May 20, 2017 at 11:40 AM,  <gareths2017 at cardensv.com> wrote:
> def calc(self, display):
>     try:
>         display.set(eval(display.get()))
>     except:
>         display.set("Type an actual equation please!")

Without any specific questions, you're not going to get anything more
than a basic eyeballing of the code. So I'm going to say this: Don't
do this! Just plain don't! A bare "except" clause is almost never the
right thing to do, and on the rare occasions when you really want to
catch everything, at very least, report on the actual error. You're
using eval(), which means that any code can be executed, which means
that literally any exception could occur. Additionally, your
try/except is around the set and get, too. Here's how I would write

def calc(self, display):
    equation = display.get()
        result = eval(equation)
    except (ValueError, TypeError):
        result = "<unsuitable data>"
    except Exception as e:
        result = "<%s: %s>" % (type(e).__name__, str(e))

That lets you give much friendlier messages on known exceptions, and
still be informative and helpful on unknown ones.