Python Google App Engine Calculator

Couple of months ago, accidentally I found myself on a conference for Python developers. I thought “what the hell am I doing here”. Ok, now I got into an interesting project and have to learn Python… 🙂

My first program – Calculator:)

import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        # build a list of operations
        f = {'+': lambda x, y: str(float(x) + float(y)),
             '-': lambda x, y: str(float(x) - float(y)),
             '*': lambda x, y: str(float(x) * float(y)),
             '/': lambda x, y: str(float(x) / float(y)),
             'C': lambda x, y: "",
            }
        # get page parameters
        x = self.request.get('x')
        y = self.request.get('y')
        operator = self.request.get('operator')
        # calculate 
        result = ""
        try:
            result = f[operator](x, y)
        except ValueError:
            result = "Error: Incorrect Number"
        except ZeroDivisionError:
            result = "Error: Division by zero"
        except KeyError:
            pass
        # build HTML response
        buttons = "".join(["<input type='submit' name='operator' value='"
                           + o + "'>" for o in sorted(f.keys())])
        self.response.out.write("""<html>
            <body>
            <form action='/' method='get' autocomplete='off'> 
            <input type='text' name='x' value='%s'/><br/>
            <input type='text' name='y'/><br/> 
            %s 
            </form>
            </body>
            </html>""" % (result, buttons))

app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s