Skip to content

Instantly share code, notes, and snippets.

@Ap0c
Last active May 10, 2017 18:47
Show Gist options
  • Save Ap0c/e5a0cd091289a524b088dfe720971c32 to your computer and use it in GitHub Desktop.
Save Ap0c/e5a0cd091289a524b088dfe720971c32 to your computer and use it in GitHub Desktop.
Calculates the total value of a pile of poker chips, because counting can be hard sometimes. Requires a json file with the chip values (colour -> number map).
# ----- Imports ----- #
import json
# ----- Setup ----- #
# This file must be json, a map of colour strings to number values.
CHIP_VALUES_FILE = 'chip-values.json'
# ----- Functions ----- #
def read_values(filename):
"""Reads in the chip values from file and returns as dict."""
with open(filename, 'r') as values_file:
chip_values = json.load(values_file)
return chip_values
def get_amount(colour, value):
"""Retrieves the amount of a colour, handles bad input."""
amount = raw_input('How many {}s? '.format(colour))
try:
return float(amount) * value
except ValueError:
print("Well that wasn't a number...")
return get_amount(colour, value)
def get_total(chip_values):
"""Gets the amount of each colour from the user and calcs the total."""
total = 0.0
for colour, value in chip_values.items():
total += get_amount(colour, value)
return total
# ----- Run ----- #
chip_values = read_values(CHIP_VALUES_FILE)
total = get_total(chip_values)
print('Your total is: {}'.format(total))
@Ap0c
Copy link
Author

Ap0c commented May 10, 2017

An example chip-values.json might be:

{
    "red": 10,
    "green": 20,
    "blue": 50
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment