Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Simple Calculator program to demonstrate use of functions for sanitized user input
- # Written on 04/18/2014 by Darryl Medley for Coding 101 on the TWiT network
- # Function that only accepts and returns a floating-point number. Optionally prints
- # a built in error message for bad values if the showErrMsg parameter is True
- def getFloat(prompt, showErrMsg):
- while True:
- try:
- return float(raw_input(prompt))
- except:
- if showErrMsg:
- print "(invalid number)"
- # end function getFloat
- # Function that only allows a character that's in the passed string of legal
- # characters to be entered. Accepts a blank / null entry if nullOk is True
- def getChar(prompt, legalValues, nullOk):
- while True:
- ch = raw_input(prompt).strip() # get entry and remove any leading and trailing whitespace
- if ch == "":
- if nullOk:
- return ch # return empty string
- else: # Something was entered.
- ch = ch[0] # [0] grabs just the first character in case a complete word is entered
- if ch in legalValues: # test to see if the character is valid
- return ch
- # end function getChar
- print "Simple Calculator"
- # Main loop
- # Since our functions are so powerful, the main routine is really simple
- while True:
- print
- fnbr1 = getFloat("Enter operand 1: ", True)
- oprnd = getChar("Enter the operator (+,-,*,/): ","+-*/", False)
- fnbr2 = getFloat("Enter operand 2: ", True)
- if (oprnd == "/") and (fnbr2 == 0.0):
- print "Division by Zero in undefined"
- else:
- # Calculate and print the result. Here we cheat and use Python's
- # eval() function that interprets a string as an expression.
- print fnbr1, oprnd, fnbr2, "=", eval(str(fnbr1)+" "+oprnd+" "+str(fnbr2))
- optn = getChar("Calculate another value (Y/No)?","YyNn",True)
- if (optn == "") or (optn not in "Yy"):
- break # exit program if not Yes (N, n or nothing entered)
- # end main loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement