Skip to content

Instantly share code, notes, and snippets.

@Cheesebaron
Created December 19, 2013 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cheesebaron/8043501 to your computer and use it in GitHub Desktop.
Save Cheesebaron/8043501 to your computer and use it in GitHub Desktop.
Just a stupid calculator
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 18:15:29 2013
@author: Tomasz
"""
import math, os
class Calc():
def __init__(self):
self.operations = {
"+" : lambda num1, num2: num1 + num2,
"-" : lambda num1, num2: num1 - num2,
"/" : lambda num1, num2: num1 / num2,
"*" : lambda num1, num2: num1 * num2,
"sqrt" : lambda num1, num2: math.sqrt(num1),
}
def main(self):
print "Simple python calculator"
print "Supports +, -, /, * and sqrt %s" % os.linesep
while True:
key, op = self.get_operation()
num1 = self.user_input()
if key == "sqrt":
print "%s %r = %r" % (key, num1, op(num1, 0))
else:
num2 = self.user_input()
print "%r %s %r = %r" % (num1, key, num2, op(num1, num2))
if not self.try_again():
break
def user_input(self):
while True:
try:
return input("Number: ")
except ValueError:
print "Didn't understand that"
def get_operation(self):
while True:
op = raw_input("Enter your operation: ").strip().lower()
try:
return op, self.operations[op]
except KeyError:
print "%s is not a known operation" % op
def try_again(self):
while True:
again = raw_input("Again? Yes/No: ").strip().lower()
if again in "yes":
return True
if again in "no":
return False
else:
print "Didn't understand %s" % again
if __name__ == '__main__':
Calc().main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment