Created
March 30, 2016 23:20
-
-
Save danielnjoo/dcd7fb0a26db19fbfb51b09ef98345ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#basic calculator | |
import re | |
import operator | |
ops = { "1": operator.add, "2": operator.sub, "3": operator.div, "4": operator.mul } | |
def error(): | |
print "Sorry you didn't input a valid command." | |
def exit_func(): | |
for i in (range(1,4)[::-1]): | |
print "Exiting in "+str(i)+"..." | |
exit() | |
def check_for_continue(answer): | |
if answer.upper()=="Y": | |
print "Continuing..." | |
return True | |
elif answer.upper()=="N": | |
exit_func() | |
else: | |
check_for_continue(raw_input("Let's try that again... Y to continue, N to exit: ")) | |
def input1(user_input): | |
if not check(user_input): #if check returns False, i.e. it's not a number... | |
error() | |
if check_for_continue(raw_input("Y to continue, N to exit: "))==True: #will loop as long as you choose to continue | |
return input1(raw_input("Choose your first number again: ")) | |
else: | |
print "First number chosen was: " + str(user_input) | |
return user_input | |
def input2(user_input): | |
if not check(user_input): | |
error() | |
if check_for_continue(raw_input("Y to continue, N to exit: "))==True: | |
return input2(raw_input("Choose your second number again: ")) | |
else: | |
print "Second number chosen was: " + str(user_input) | |
return user_input | |
def operator(user_input): | |
if user_input == "+": | |
return ops["1"] | |
elif user_input == "-": | |
return ops["2"] | |
elif user_input == "/": | |
return ops["3"] | |
elif user_input == "*": | |
return ops["4"] | |
else: | |
error() | |
if (check_for_continue(raw_input("Y to continue, N to exit: ")))==True: | |
return operator(raw_input("Choose your operator again: ")) | |
def check(user_input): | |
match = re.search("\D", user_input) #re is a regex module, and \D returns True for non-digits | |
if not match: | |
return True | |
else: | |
return False | |
def in_use(user_input): | |
if user_input.upper()=="Y": | |
print "\nCalculator 1.0 up and running, note only integers and basic mathematical operations allowed." | |
a=int(input1(raw_input("First number: "))) | |
b=int(input2(raw_input("Second number: "))) | |
print operator(raw_input("Choose an operator: "))(a,b) | |
in_use(raw_input("Y to use it again, N to quit: ")) | |
if user_input.upper()=="N": | |
exit_func() | |
else: | |
print "I didn't quite catch that... Again?" | |
in_use(raw_input("Y to use it, N to quit: ")) | |
in_use(raw_input("Y to turn on the calculator, N to quit: ")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment