Skip to content

Instantly share code, notes, and snippets.

@emilepetrone
Forked from anonymous/calc_functions.py
Created June 10, 2012 23:58
Show Gist options
  • Save emilepetrone/2907768 to your computer and use it in GitHub Desktop.
Save emilepetrone/2907768 to your computer and use it in GitHub Desktop.
class ConvertError(ValueError):
message = 'Whoops - one of the values you entered cannot be converted to something that will work for these calculations. Try this again.'
class BadStuff(BaseException):
message = 'Something went wrong with this calculation. Maybe try passing in new values.'
class Zero(ZeroDivisionError):
message = 'Yeah, dividing with a 0 in the mix does not work.'
def try_division(value_list):
try:
return dividing(value_list)
except Zero as a:
zero_error = a.message
return zero_error
def adding(value_list):
new_value = 0
for value in value_list:
new_value += value
return new_value
def subtracting(value_list):
new_value = 0
for value in value_list:
new_value -= value
return new_value
def multiplying(value_list):
new_value = 1
for value in value_list:
new_value *= value
return new_value
def dividing(value_list):
new_value = 1
for value in value_list:
new_value /= value
return new_value
from django.http import HttpResponse
from django.shortcuts import render
import calc_functions
def call_calc_functions(value_list):
calculations = [
(calc_functions.adding, 'Adding all of the values:'),
(calc_functions.subtracting, 'Subtracting all of the values:'),
(calc_functions.multiplying, 'Multiplying all of the values:'),
(calc_functions.try_division, 'Dividing all of the values:'),
]
results = [((method(value_list), header)) for method, header in calculations]
return results
def do_math(request):
context = {
'heading': 'Here are some calculations based '
'on the information provided in '
'the URL for this page:',
}
try:
value_list = [(float(value)) for key, value in request.GET.iteritems()]
except calc_functions.ConvertError as x:
convert_error = x.message
context['convert_error'].append(convert_error)
else:
context['params'] = value_list
try:
result = call_calc_functions(value_list)
except calc_functions.BadStuff as e:
error = e.message
context['error'] = error
else:
context['results'] = result
return render(request, 'calculations.html', context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment