-
-
Save emilepetrone/2907768 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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