Skip to content

Instantly share code, notes, and snippets.

@newtoallofthis123
Created May 10, 2023 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newtoallofthis123/070f9f34f2f37bdea305a97277f6a7b1 to your computer and use it in GitHub Desktop.
Save newtoallofthis123/070f9f34f2f37bdea305a97277f6a7b1 to your computer and use it in GitHub Desktop.
One of my first python programs
import json
import re
import argparse
int_to_str_seperator = re.compile("([a-zA-Z]+)([0-9]+)")
parser = argparse.ArgumentParser()
parser.add_argument("molecular_formula",help="Give the molecular formula in the syntax 'C12|H12|OH1'")
args = parser.parse_args()
def calculator(e):
with open('atomic_weights.json', 'r') as file:
content = file.read()
atomic_weights = json.loads(content)
atom_raw = e.split("|")
atoms = dict()
for i in atom_raw:
atom = int_to_str_seperator.match(i).groups()
atomic_weight = atomic_weights[str.lower(atom[0])]
weight = atomic_weight * int(atom[1])
atoms[atom[0]] = weight
print(f'Atomic Weight of {e}: {sum(atoms.values())}')
atom_to_calculate = args.molecular_formula
calculator(atom_to_calculate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment