Created
June 7, 2022 06:21
-
-
Save mike-pete/714d8293c0579b03289a9d3e5e84a8fe to your computer and use it in GitHub Desktop.
Baking conversions in Python
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
conversions = { | |
'cup': 1, | |
'ml': 236.588, | |
'tbsp': 16, | |
'tsp': 48 | |
} | |
unitAlias = { | |
'cups': 'cup', | |
'mls': 'ml', | |
'mililiter': 'ml', | |
'mililiters': 'ml', | |
'tsps': 'tsp', | |
'teaspoon': 'tsp', | |
'teaspoons': 'tsp', | |
'tbsps': 'tbsp', | |
'tablespoon': 'tbsp', | |
'tablespoons': 'tbsp', | |
} | |
def convertToCups(unitToConvertFrom, amountOfUnit): | |
conversionRate = conversions[unitToConvertFrom] | |
numberOfCups = amountOfUnit/conversionRate | |
return numberOfCups | |
def convertFromCups(unitToConvertTo, numberOfCups): | |
conversionRate = conversions[unitToConvertTo] | |
numberOfUnits = numberOfCups*conversionRate | |
return numberOfUnits | |
def convertBetweenUnits(unitIn, amount, unitOut): | |
if (unitOut == 'cup'): | |
return convertToCups(unitIn, amount) | |
elif (unitIn == 'cup'): | |
return convertFromCups(unitOut, amount) | |
else: | |
cups = convertToCups(unitIn, amount) | |
return convertFromCups(unitOut, cups) | |
def getOfficialUnitName(unit): | |
if unit in conversions: | |
return unit | |
elif unit in unitAlias: | |
officialUnitName = unitAlias[unit] | |
return officialUnitName | |
else: | |
return False | |
def verifyNumericInput(input): | |
try: | |
inputAsANumber = float(input) | |
if inputAsANumber > 0: | |
return inputAsANumber | |
except: | |
return False | |
def getInput(prompt, inputValidator): | |
validInput = False | |
# do this instead of while True: | |
while not validInput: | |
userInput = input(prompt) | |
validInput = inputValidator(userInput) | |
return validInput | |
# main functions are pretty neat | |
def main(): | |
unitIn = getInput('What are you converting from?\n', getOfficialUnitName) | |
amount = getInput('\nHow much do you have?\n', verifyNumericInput) | |
unitOut = getInput('\nWhat are you converting to?\n', getOfficialUnitName) | |
unitOutAmount = convertBetweenUnits(unitIn, amount, unitOut) | |
print(f'{amount} ({unitIn}) => {unitOutAmount} ({unitOut})') | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment