Advertisement
Darryl-Medley

CalcEntryDemo

Apr 18th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. # Simple Calculator program to demonstrate use of functions for sanitized user input
  2. # Written on 04/18/2014 by Darryl Medley for Coding 101 on the TWiT network
  3.  
  4. # Function that only accepts and returns a floating-point number. Optionally prints
  5. # a built in error message for bad values if the showErrMsg parameter is True
  6. def getFloat(prompt, showErrMsg):
  7.     while True:
  8.         try:
  9.             return float(raw_input(prompt))
  10.         except:
  11.             if showErrMsg:
  12.                 print "(invalid number)"
  13. # end function getFloat
  14.  
  15. # Function that only allows a character that's in the passed string of legal
  16. # characters to be entered. Accepts a blank / null entry if nullOk is True
  17. def getChar(prompt, legalValues, nullOk):
  18.     while True:
  19.         ch = raw_input(prompt).strip()   # get entry and remove any leading and trailing whitespace
  20.         if ch == "":
  21.             if nullOk:
  22.                 return ch   # return empty string
  23.         else:   # Something was entered.
  24.             ch = ch[0]   # [0] grabs just the first character in case a complete word is entered
  25.             if ch in legalValues:   # test to see if the character is valid
  26.                 return ch
  27. # end function getChar
  28.  
  29.  
  30. print "Simple Calculator"
  31.  
  32. # Main loop
  33. # Since our functions are so powerful, the main routine is really simple
  34. while True:
  35.     print
  36.     fnbr1 = getFloat("Enter operand 1: ", True)
  37.     oprnd = getChar("Enter the operator (+,-,*,/): ","+-*/", False)
  38.     fnbr2 = getFloat("Enter operand 2: ", True)
  39.  
  40.     if (oprnd == "/") and (fnbr2 == 0.0):
  41.         print "Division by Zero in undefined"
  42.     else:
  43.         # Calculate and print the result. Here we cheat and use Python's
  44.         # eval() function that interprets a string as an expression.
  45.         print fnbr1, oprnd, fnbr2, "=", eval(str(fnbr1)+" "+oprnd+" "+str(fnbr2))
  46.  
  47.     optn = getChar("Calculate another value (Y/No)?","YyNn",True)
  48.     if (optn == "") or (optn not in "Yy"):
  49.         break   # exit program if not Yes (N, n or nothing entered)
  50.        
  51. # end main loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement