mercredi 21 janvier 2015

Pythonic way to write calculate function for a calculator - Python

I am creating a text calculator that does not work completely conventionally. It works like this:



  • Operation Input: The user inputs the operation the calculator will process (+ for addition, - for subtraction, * for multiplication, or / for division)

  • Operand Input: The user inputs in each operand of the calculation, pressing Return between operands. Once the user has inputted all of his desired operands, striking Return three times initiates calculation.


Calculation:


When a user enters in more than two operands, instead of doing:


operand1 plus/minus/times/divided by operand2,


It does:


operand1 plus/minus/times/divided by operand2 plus/minus/times/divided by operand3,


And so on for all of the inputted operands.


The code for this simply loops through the list of inputted operands, operandList, and uses the chosen operation, operation (and result is the result of the calculation):



def Calculate():
global operation, operandList, result
operateCount = 0
result = 0
while operateCount < len(operandList):
if operation == '+':
result += operandList[operateCount]
elif operation == '-':
result -= operandList[operateCount]
elif operation == '*':
result *= operandList[operateCount]
elif operation == '/':
result /= operandList[operateCount]
operateCount += 1

if operation == '+':
resultName = 'Sum'
elif operation == '-':
resultName = 'Difference'
elif operation == '*':
resultName = 'Product'
elif operation == '/':
resultName = 'Quotient'

if result.is_integer():
print(int(result), '=', resultName)
else:
print(result, '=', resultName)
print()


This is super inefficient because it checks for the operation twice, and once inside the while loop, which is even worse.


Obviously if I write one of those while loop blocks for each operation and begin each one with an if statement to check for the operation that is much worse.


If I did that you would see that the only difference between each block of code is the operation sign in result +,-,*,/= operandList[operateCount].


How can I:



  • Cut out the redundant code that checks for the operation and executes the respective loop, and

  • Reduce/ change the redundant code that checks for the operation when it displays the result?


Any help is greatly appreciated. Please ask for specifications if necessary. And if you down vote, please comment your reason for doing so so I can make changes.


Aucun commentaire:

Enregistrer un commentaire