The periodic table of the elements organizes all known chemical elements into a single table. This program presents this table and lets the player access additional information about each element, such as its atomic number, symbol, melting point, and so on. I compiled this information from Wikipedia and stored it in a file called periodictable.csv that you can download from https://inventwithpython.com/periodictable.csv.
When you run periodictable.py, the output will look like this:
Periodic Table of Elements
By Al Sweigart [email protected]
Periodic Table of Elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 H He
2 Li Be B C N O F Ne
3 Na Mg Al Si P S Cl Ar
4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr
5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe
6 Cs Ba La Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn
7 Fr Ra Ac Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og
Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu
Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr
Enter a symbol or atomic number to examine, or QUIT to quit.
> 42
Atomic Number: 42
Symbol: Mo
Element: Molybdenum
Origin of name: Greek molýbdaina, 'piece of lead', from mólybdos, 'lead'
Group: 6
Period: 5
Atomic weight: 95.95(1) u
Density: 10.22 g/cm^3
Melting point: 2896 K
Boiling point: 4912 K
Specific heat capacity: 0.251 J/(g*K)
Electronegativity: 2.16
Abundance in earth's crust: 1.2 mg/kg
Press Enter to continue...
--snip--
A .csv, or comma-separated values, file is a text file that represents a primitive spreadsheet. Each line in the .csv file is a row, and commas separate the columns. For example, the first three lines in periodictable.csv look like this:
1,H,Hydrogen,"Greek elements hydro- and -gen, meaning 'water-forming--snip--
2,He,Helium,"Greek hḗlios, 'sun'",18,1,4.002602(2)[III][V],0.0001785--snip--
3,Li,Lithium,"Greek líthos, 'stone'",1,2,6.94[III][IV][V][VIII][VI],--snip--
Python’s csv
module makes it easy to import data from a .csv file and into a list of lists of strings, as lines 15 to 18 do. Lines 32 to 58 turn this list of lists into a dictionary so that the rest of the program can easily summon the information by an element’s name or atomic number.
1. """Periodic Table of Elements, by Al Sweigart [email protected]
2. Displays atomic information for all the elements.
3. This code is available at https://nostarch.com/big-book-small-python-programming
4. Tags: short, science"""
5.
6. # Data from https://en.wikipedia.org/wiki/List_of_chemical_elements
7. # Highlight the table, copy it, then paste it into a spreadsheet program
8. # like Excel or Google Sheets like in https://invpy.com/elements
9. # Then save this file as periodictable.csv.
10. # Or download this csv file from https://invpy.com/periodictable.csv
11.
12. import csv, sys, re
13.
14. # Read in all the data from periodictable.csv.
15. elementsFile = open('periodictable.csv', encoding='utf-8')
16. elementsCsvReader = csv.reader(elementsFile)
17. elements = list(elementsCsvReader)
18. elementsFile.close()
19.
20. ALL_COLUMNS = ['Atomic Number', 'Symbol', 'Element', 'Origin of name',
21. 'Group', 'Period', 'Atomic weight', 'Density',
22. 'Melting point', 'Boiling point',
23. 'Specific heat capacity', 'Electronegativity',
24. 'Abundance in earth\'s crust']
25.
26. # To justify the text, we need to find the longest string in ALL_COLUMNS.
27. LONGEST_COLUMN = 0
28. for key in ALL_COLUMNS:
29. if len(key) > LONGEST_COLUMN:
30. LONGEST_COLUMN = len(key)
31.
32. # Put all the elements data into a data structure:
33. ELEMENTS = {} # The data structure that stores all the element data.
34. for line in elements:
35. element = {'Atomic Number': line[0],
36. 'Symbol': line[1],
37. 'Element': line[2],
38. 'Origin of name': line[3],
39. 'Group': line[4],
40. 'Period': line[5],
41. 'Atomic weight': line[6] + ' u', # atomic mass unit
42. 'Density': line[7] + ' g/cm^3', # grams/cubic cm
43. 'Melting point': line[8] + ' K', # kelvin
44. 'Boiling point': line[9] + ' K', # kelvin
45. 'Specific heat capacity': line[10] + ' J/(g*K)',
46. 'Electronegativity': line[11],
47. 'Abundance in earth\'s crust': line[12] + ' mg/kg'}
48.
49. # Some of the data has bracketed text from Wikipedia that we want to
50. # remove, such as the atomic weight of Boron:
51. # "10.81[III][IV][V][VI]" should be "10.81"
52.
53. for key, value in element.items():
54. # Remove the [roman numeral] text:
55. element[key] = re.sub(r'\[(I|V|X)+\]', '', value)
56.
57. ELEMENTS[line[0]] = element # Map the atomic number to the element.
58. ELEMENTS[line[1]] = element # Map the symbol to the element.
59.
60. print('Periodic Table of Elements')
61. print('By Al Sweigart [email protected]')
62. print()
63.
64. while True: # Main program loop.
65. # Show table and let the user select an element:
66. print(''' Periodic Table of Elements
67. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
68. 1 H He
69. 2 Li Be B C N O F Ne
70. 3 Na Mg Al Si P S Cl Ar
71. 4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr
72. 5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe
73. 6 Cs Ba La Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn
74. 7 Fr Ra Ac Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og
75.
76. Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu
77. Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr''')
78. print('Enter a symbol or atomic number to examine, or QUIT to quit.')
79. response = input('> ').title()
80.
81. if response == 'Quit':
82. sys.exit()
83.
84. # Display the selected element's data:
85. if response in ELEMENTS:
86. for key in ALL_COLUMNS:
87. keyJustified = key.rjust(LONGEST_COLUMN)
88. print(keyJustified + ': ' + ELEMENTS[response][key])
89. input('Press Enter to continue...')
Try to find the answers to the following questions. Experiment with some modifications to the code and rerun the program to see what effect the changes have.
response == 'Quit'
on line 81 to response == 'quit'
?