W04 Project: Chemistry
Purpose
Prove that you can write a Python program that creates and uses compound lists.
Project
Background
You are an intern working for a government research facility. The chemistry lab has requested a program that will calculate the molar mass and the number of moles for a given quantity of a chemical compound. You have been assigned to create this program.
Often times you will be tasked to create programs where you might not fully understand the entire problem. When this happens you must rely on the requirements given to you by the user. For this problem you may not know what a mole or a molar mass is. Don't worry. The user knows what they are and can give you the necessary information to solve their problem.
User Requirements
The lead chemist Mariana Cardoso has asked you to create a program with the following requirements.
- Ask the user for a chemical formula.
- Ask the user for the amount of the compound in grams (this is the sample_mass).
- Compute and display the molar mass.
- Compute and display the number of moles.
Mariana has provided the following information:
- A compound or molecule is described by a list of elements it contains. The element is identified by the element's symbol. If there is more than one atom of that element a number representing the number of atoms in the compound will follow the element's symbol. Here are some examples.
- H2O (water) has 2 Hydrogen atoms and 1 Oxygen atom.
- C6H12O6 (glucose) has 6 Carbon atoms, 12 Hydrogen atoms, and 6 Oxygen atoms.
-
To calculate the molar mass of a compound all you need to do is sum all of the weights of each atom in the compound.
-
To calculate the number of moles in a sample use the following formula:number_of_moles =sample_massmolar_mass
Design
The requirements were sent to Alice Laurent, one of our software architects. She provided the following direction.
Alice developed the following program architecture. Use this information to create your program. As a junior programmer, you must use the functions defined by Alice, and the exact function names and parameters.
Function Specifications
Function Name ParametersReturn Type Description make_periodic_table Parameters: (none) Returns: Dictionary Returns a dictionary object which contains all of the elements of the periodic table. - For each element the dictionary key should be the element's symbol.
- The value contains a list where the first item in the list is the element's name and the second item is the atomic mass.
compute_molar_mass Parameters: symbol_quantity_list, periodic_table_dict Returns: float Compute and return the total molar mass of all the elements listed in symbol_quantity_list. - loop through the item's in the symbol_quantity_list
- For each item in the list use the element's symbol to lookup the atomic mass of the element in the periodic_table_dict dictionary.
- Multiply the elements atomic weight by the quantity of atoms for the element (from the symbol_quantity_list) and add that to the total mass.
- Return the total mass.
main Parameters: (none) Returns: (none) - Asks the user for a chemical formula.
- Asks the user for the sample size in grams.
- Call parse_formula (from provided library) to get a list of elements in formula. (store in a vaiable).
- Call make_periodic_table function and store returned dictionary in variable.
- Call compute_molar_mass to calculate the molar mass. Pass in the periodic table dictionary and element list returned from the previous functions.
- Display the molar mass.
- Calculate Number of moles in the sample.
- Display the Number of moles.
Other helpful information.
While working on this project Alice discoverd that another programmer has already created a library that has a function named
parse_formula
for another project. This function does exactly what you need. You can use that library in your program to save time. The function is in the libraryformula.py
Milestone
Start your project by writing the outline of your program. Follow these steps:
- Create a folder for this week's project, name it whatever you want.
- Open the folder you just created in VSCode.
- Create a file named chemistry.py.
- Create the function
make_periodic_table
. When complete the function will return a dictionary that contains all of the elements in the periodic table. Your dictionary should look similar to this:periodic_table_dict = { # symbol: [name, atomic_mass] "Ac": ["Actinium", 227], "Ag": ["Silver", 107.8682], "Al": ["Aluminum", 26.9815386], ⋮ }
Full list of elements:
Mariana has provided this list of elements for you to use. It is also available in this text file elements.csvSymbol Name Atomic Mass Ac, Actinium, 227 Ag, Silver, 107.8682 Al, Aluminum, 26.9815386 Ar, Argon, 39.948 As, Arsenic, 74.9216 At, Astatine, 210 Au, Gold, 196.966569 B, Boron, 10.811 Ba, Barium, 137.327 Be, Beryllium, 9.012182 Bi, Bismuth, 208.9804 Br, Bromine, 79.904 C, Carbon, 12.0107 Ca, Calcium, 40.078 Cd, Cadmium, 112.411 Ce, Cerium, 140.116 Cl, Chlorine, 35.453 Co, Cobalt, 58.933195 Cr, Chromium, 51.9961 Cs, Cesium, 132.9054519 Cu, Copper, 63.546 Dy, Dysprosium, 162.5 Er, Erbium, 167.259 Eu, Europium, 151.964 F, Fluorine, 18.9984032 Fe, Iron, 55.845 Fr, Francium, 223 Ga, Gallium, 69.723 Gd, Gadolinium, 157.25 Ge, Germanium, 72.64 H, Hydrogen, 1.00794 He, Helium, 4.002602 Hf, Hafnium, 178.49 Hg, Mercury, 200.59 Ho, Holmium, 164.93032 I, Iodine, 126.90447 In, Indium, 114.818 Ir, Iridium, 192.217 K, Potassium, 39.0983 Kr, Krypton, 83.798 La, Lanthanum, 138.90547 Li, Lithium, 6.941 Lu, Lutetium, 174.9668 Mg, Magnesium, 24.305 Mn, Manganese, 54.938045 Mo, Molybdenum, 95.96 N, Nitrogen, 14.0067 Na, Sodium, 22.98976928 Nb, Niobium, 92.90638 Nd, Neodymium, 144.242 Ne, Neon, 20.1797 Ni, Nickel, 58.6934 Np, Neptunium, 237 O, Oxygen, 15.9994 Os, Osmium, 190.23 P, Phosphorus, 30.973762 Pa, Protactinium, 231.03588 Pb, Lead, 207.2 Pd, Palladium, 106.42 Pm, Promethium, 145 Po, Polonium, 209 Pr, Praseodymium, 140.90765 Pt, Platinum, 195.084 Pu, Plutonium, 244 Ra, Radium, 226 Rb, Rubidium, 85.4678 Re, Rhenium, 186.207 Rh, Rhodium, 102.9055 Rn, Radon, 222 Ru, Ruthenium, 101.07 S, Sulfur, 32.065 Sb, Antimony, 121.76 Sc, Scandium, 44.955912 Se, Selenium, 78.96 Si, Silicon, 28.0855 Sm, Samarium, 150.36 Sn, Tin, 118.71 Sr, Strontium, 87.62 Ta, Tantalum, 180.94788 Tb, Terbium, 158.92535 Tc, Technetium, 98 Te, Tellurium, 127.6 Th, Thorium, 232.03806 Ti, Titanium, 47.867 Tl, Thallium, 204.3833 Tm, Thulium, 168.93421 U, Uranium, 238.02891 V, Vanadium, 50.9415 W, Tungsten, 183.84 Xe, Xenon, 131.293 Y, Yttrium, 88.90585 Yb, Ytterbium, 173.054 Zn, Zinc, 65.38 Zr, Zirconium, 91.224 - Add function
main
. For now just have the main function call make_periodic_table and print the returned table.- Include the following code at the bottom of your program to facilitate testing.
if __name__ == "__main__": main()
Testing
Verify that your program works correctly by following each step in this testing procedure:
Download the
test_chemistry_milestone.py
Python file and save it in the same folder where you saved yourchemistry.py
program. Run thetest_chemistry_milestone.py
file and ensure that the test passes. If the test functions does not pass, there is a mistake in yourchemistry.py
program. Read the output frompytest
, fix the mistake, and run thetest_chemistry_milestone.py
file again until all the test functions pass.============================== 1 passed in 0.04s ============================== PS C:\Users\cjlindstrom\cse111\chemistry> python .\test_chemistry_milestone.py ============================= test session starts ============================= platform win32 -- Python 3.13.0, pytest-8.3.4, pluggy-1.5.0 cachedir: .pytest_cache rootdir: C:\Users\cjlindstrom\cse111\chemistry collected 1 item test_chemistry_milestone.py::test_make_periodic_table PASSED [100%] ============================== 1 passed in 0.04s ==============================
Milestone Submission
On or before the due date, return to Canvas and report your progress on this milestone.
Project Completion
Finish your project by completing the code for the
compute_molar_mass
andmain
functions. Ensure your code accomplishes the requirements specified above.-
Download the
formula.py
Python file and save it in the same folder where you saved yourchemistry.py
program. Theformula.py
file includes aFormulaError
class and a function namedparse_formula
. Both of them are complete and work correctly, and you should not change them. -
Open the
formula.py
file in VS Code and read the triple quoted string at the top of theparse_formula
function. As the triple quoted string states, theparse_formula
function converts a chemical formula for a molecule, such as "C13H16N2O2" (melatonin), into a compound list, such as [["C", 13], ["H", 16], ["N", 2], ["O", 2]]. This compound list is known as a symbol_quantity_list because it contains the symbols of chemical elements and the quantity of atoms of each element that appear in a chemical formula. -
Copy and paste the following import statement into your
chemistry.py
program at the top of your program. This statement will import theparse_formula
function from theformula.py
file into yourchemistry.py
program so that you can call theparse_formula
function in your program.from formula import parse_formula
- Complete the
compute_molar_mass
function according to the program specifications.Calculation Example:
This example might help you as you write your code. Consider a sample of glucose (C6H12O6) with a mass of 12.37 grams. To use a molar mass calculator, a chemist enters
-
C6H12O6
-
12.37
The calculator computes the molar mass of glucose by doing the following:
-
Sum the number of atoms of each element in the formula for glucose:
6 carbon atoms
12 hydrogen atoms
6 oxygen atoms -
Find the atomic mass of each element:
Symbol Name Atomic Mass C Carbon 12.0107 H Hydrogen 1.00794 O Oxygen 15.9994 -
Multiply the number of atoms by their atomic mass:
6 × 12.0107 = 72.0642 12 × 1.00794 = 12.09528 6 × 15.9994 = 95.9964 -
Add the results of the multiplications to get the molar mass of glucose:72.0642 + 12.09528 + 95.9964 = 180.15588 grams/mole
Then the calculator divides the mass of the sample of glucose by the molar mass of glucose which results in the number of moles in the sample:
12.37 grams180.15588 grams/moleThe calculator prints two results for the chemist to see:
-
the molar mass of glucose: 180.15588 grams/mole
-
the number of moles in the sample: 0.06866 moles
Hint: Don't forget index variables.
Remember when working with compound lists is is helpful to create variables that hold the index values of your data. For example, if I had a list that contains lists that describe people and their favorite color:
The following code will print each person's name and favorite color.people=[['James','red'],['Julia','blue'],['Ricardo','yellow']]
If I use well named variables to hold the list index numbers my code is much easier to understand.for person in people: print(f"{person[0]}'s favorite color is {person[1]}")
NAME_INDEX=0 COLOR_INDEX=1 for person in people: print(f"{person[NAME_INDEX]}'s favorite color is {person[COLOR_INDEX]}")
-
- Complete the
main
function. Remove the code from the milestone and complete the main function according to the program Specifications.
Exceeding the Requirements
If your program fulfills the requirements for this assignment as described above, your program will earn 93% of the possible points. In order to earn the remaining 7% of points, you will need to add one or more features to your program so that it exceeds the requirements. Use your creativity to add features. Add a comment to the top of your code that explains your enhancement(s).
Document your enhancements:If you choose to "exceed requirements" place a comment at the top of your code file that describes what you did to enhance your program.
Testing
Verify that your program works correctly by following each step in this testing procedure:
-
Download the
test_chemistry.py
Python file and save it in the same folder where you saved yourchemistry.py
program. Run thetest_chemistry.py
file and ensure that all three of the test functions pass. If any of the test functions don’t pass, there is a mistake in yourchemistry.py
program. Read the output frompytest
, fix the mistake, and run thetest_chemistry.py
file again until all the test functions pass.> python test_chemistry_2.py =================== test session starts ==================== platform win32--Python 3.8.6, pytest-6.1.2, py-1.9.0, pluggy rootdir: C:\Users\cse111\week04 collected 3 items test_chemistry_2.py::test_make_periodic_table PASSED [ 33%] test_chemistry_2.py::test_parse_formula PASSED [ 66%] test_chemistry_2.py::test_compute_molar_mass PASSED [100%] ==================== 3 passed in 0.17s =====================
-
Run your finished
chemistry.py
program. Enter the input shown below and ensure that your program prints the output shown below.> python chemistry.py Enter the molecular formula of the sample: C6H6 Enter the mass in grams of the sample: 25.04 78.11184 grams/mole 0.32057 moles
Project Submission
Return to Canvas and upload your
chemistry.py
file for feedback.Don't get a zero!If an error prevents your program from running to completion the grader will score your assignment with a 0 and request that you fix and resubmit your program. In other words, rather than submitting a program that doesn't work, it's best to ask for help to understand how to fix the problem before submitting your program.
Useful Links:
- Return to: Week Overview | Course Home
- Add function