Advertisement
brilliant_moves

Calc.py

Aug 24th, 2014
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. #!/usr/bin/python
  2. #Module: Calc.py (a.k.a. Calcul8.py)
  3. #Purpose: Calculator program
  4. #Language: Python 2.7
  5. #Author: Chris Clarke
  6. #Date: 24.08.2014
  7.  
  8. import sys
  9.  
  10. def calc(first, operator, second):
  11.     ans = 0
  12.     if operator == '+':
  13.         ans = first + second
  14.     elif operator == '-':
  15.         ans = first - second
  16.     elif operator in {'*', 'x', 'X'}:
  17.         ans = first * second
  18.     elif operator == '/':
  19.         if second != 0:
  20.             ans = first / second
  21.         else:
  22.             print_error("Can't divide by zero!")
  23.     elif operator == '%':
  24.         if second != 0:
  25.             ans = first % second
  26.         else:
  27.             print_error("Can't do modulo zero!")
  28.     elif operator == '^' or  operator == '**':
  29.         ans = first ** second
  30.     return ans
  31.    
  32. def print_error(error):
  33.     print error
  34.     sys.exit(1)
  35.  
  36. def get_number(message):
  37.     while True:
  38.         try:
  39.             number = float(raw_input(message))
  40.         except ValueError:
  41.             print "Not a number"
  42.         else:
  43.             return number
  44.  
  45. title =  "*** Calc u L8r! ***"
  46.  
  47. print title
  48. first = get_number("Enter first number: ")
  49. first_time = True
  50. while True:
  51.     if first_time:
  52.         prompt = "Enter operator (+,-,*,/,%,^): "
  53.         first_time = False
  54.     else:
  55.         prompt = "Enter operator (+,-,*,/,%,^,(n)ew,(q)uit): "
  56.     operator = raw_input(prompt)
  57.     if operator in {'n', 'new'}:
  58.         first = 0.0
  59.         print "\nResult:", first
  60.         first = get_number("Enter first number: ")
  61.         continue
  62.     if operator in {'q', 'quit'}:
  63.         print "Quitting program..."
  64.         print title
  65.         break
  66.     if not operator in {'+','-','*','x','X','/','%','^','**'}:
  67.         print "Invalid operator!"
  68.         continue
  69.     second = get_number("Enter second number: ")
  70.     first = calc(first, operator, second)
  71.     print "\nResult:", first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement