Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- #Module: Calc.py (a.k.a. Calcul8.py)
- #Purpose: Calculator program
- #Language: Python 2.7
- #Author: Chris Clarke
- #Date: 24.08.2014
- import sys
- def calc(first, operator, second):
- ans = 0
- if operator == '+':
- ans = first + second
- elif operator == '-':
- ans = first - second
- elif operator in {'*', 'x', 'X'}:
- ans = first * second
- elif operator == '/':
- if second != 0:
- ans = first / second
- else:
- print_error("Can't divide by zero!")
- elif operator == '%':
- if second != 0:
- ans = first % second
- else:
- print_error("Can't do modulo zero!")
- elif operator == '^' or operator == '**':
- ans = first ** second
- return ans
- def print_error(error):
- print error
- sys.exit(1)
- def get_number(message):
- while True:
- try:
- number = float(raw_input(message))
- except ValueError:
- print "Not a number"
- else:
- return number
- title = "*** Calc u L8r! ***"
- print title
- first = get_number("Enter first number: ")
- first_time = True
- while True:
- if first_time:
- prompt = "Enter operator (+,-,*,/,%,^): "
- first_time = False
- else:
- prompt = "Enter operator (+,-,*,/,%,^,(n)ew,(q)uit): "
- operator = raw_input(prompt)
- if operator in {'n', 'new'}:
- first = 0.0
- print "\nResult:", first
- first = get_number("Enter first number: ")
- continue
- if operator in {'q', 'quit'}:
- print "Quitting program..."
- print title
- break
- if not operator in {'+','-','*','x','X','/','%','^','**'}:
- print "Invalid operator!"
- continue
- second = get_number("Enter second number: ")
- first = calc(first, operator, second)
- print "\nResult:", first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement