Chapter 0
Table of Contents
- Data
- Code blocks from chapter
- Solutions to Exercises
- Giving your computer instructions using Python commands
- Having Python do basic math by evaluating mathematical expressions
- Having Python do basic math by evaluating mathematical expressions
- Clarifying how your code works with comments
- Temporarily storing data using variables
- Expressing_data_as_readable_text_using_strings
- Avoiding repetitive typing by making your own functions
Data
There is no data required for or used in Chapter 0.
Code blocks from chapter
# A function to calculate the volumes of stock solutions needed to create solutions with given catalyst, HCl, and ionic strength
# All concentrations are in M
# The final volume is in mL and assumed to be 1 unless provided
def calcPlateVols(conc_cat, conc_HCl, I, vol_final = 1):
# Define our stock solutions
conc_stock_cat = 0.1 # M
conc_stock_HCl = 6 # M
conc_stock_NaCl = 3 # M
# Calculate the volumes needed
vol_cat = conc_cat / conc_stock_cat * vol_final
vol_HCl = conc_HCl / conc_stock_HCl * vol_final
vol_NaCl = (I - conc_HCl) / conc_stock_NaCl * vol_final
# Calculate the water needed to make up 1 mL
vol_water = vol_final - vol_cat - vol_HCl - vol_NaCl
print('[ ] catalyst solution (mL)\n', vol_cat)
print('[ ] HCl (mL)\n', vol_HCl)
print('[ ] NaCl (mL)\n', vol_NaCl)
print('[ ] water (mL)\n', vol_water)Solutions to Exercises
Giving your computer instructions using Python commands
Exercise 0
Using Anaconda Navigator, verify that the following Python libraries are installed, and if not, install them. If you want directions you can use the resources at website.
- numpy
- scipy
- lmfit
- plotly
- kaleido
- pillow
- openpyxl
- python-docx
- rdkit
- nbformat
- codechembook
You can check to see what libraries are installed using conda list in the Windows Command Line or Mac Terminal. A sample partial output:
At the time of writing this problem, it was:
- Spyder = 5.5.1
- Numpy = 1.26.4
- scipy = 1.13.1
- Plotly = 5.24.1
- Pillow = 10.4.0
- openpyxl = 3.1.5
- lmfit = 1.3.2
- python-docx = 1.1.2
- python-kaliedo = 0.1.0
- codechembook = 1.0.1
- RDKit = 2024.03.5
The set of numbers are the version numbers, which you can compare to the required minimum versions for the book.
Exercise 1
Run plotly-test.py from the codechembook library. If you need more directions, refer to the resources at website
There are two possible ways to do this:
- in the Python interpreter (using IDLE or by running
python.exe(Windows) in the command line orpython3(Macs) in the Terminal), typeplotly_testand press enter. - in the Windows command line, type
python.exe plotly_test.pyand press Enter or in the Mac Terminal, typepython3 plotly_test.pyand press return.
Having Python do basic math by evaluating mathematical expressions
Exercise 2
Compute the following outside of Python, and then have Python compute them. Compare the answers:
- $9^{1/2}$
- $9^{0.5}$
- $5 + \frac{7}{8}$
- $5 + 7\div 8$
- $(5 + 7) \div 8$
- $(4 + 5)^{1/2}$
- $9 \div 3^2$
- $2^{3+1}$
See below for analytical : Python solutions.
a. $9^{1/2} = \sqrt{9} = 3$ : 9**(1/2) = 3
b. $9^0.5 = 9^{1/2} = 3$ : 9**0.5 = 3
c. $5 + \frac{7}{8} = 5 + .875 = 5.875$ : 5 + (7/8) = 5.875
d. $5 + 7 / 8 = 5 + \frac{7}{8} = 5.875$ : 5 + 7 / 8 = 5.875
e. $(5 + 7) / 8 = 12/8 = 1.5$ : (5 + 7) / 8 = 1.5
f. $(4 + 5)^{1/2} = 9^{1/2} = 3$ : (4+5)**(1/2) = 1.5
g. $9 \div 3^2 = 9 \div 9 = 1$ : 9 / 3**2 = 1
h. $2^{3+1} = 2^4 = 16$ : 2**(3 + 1) = 16
Having Python do basic math by evaluating mathematical expressions
Exercise 3
Compute the following outside of Python, and then have Python compute them. Compare the answers:
- $2 - 3$
- $|3-2|$
- $4.5 +3.2 \times 7.8-12.1$
- $(4.5 +3.2) \times (7.8-12.1)$
- $(4.5 +3.2) \times (|7.8-12.1|)$
See below for analytical : Python solutions.
a. $2 - 3 = -1$ : 2 - 3 = -1
b. $|2 - 3| = 1$ : abs(2-3) = 1
c. $4.5 + 3.2 \times 7.8 - 12.1 = 4.5 + 24.96 - 12.1 = 29.46 - 12.1 = 17.46$ : 4.5 + 3.2 * 7.8 - 12.1 = 17.46
d. $(4.5 + 3.2) \times (7.8 - 12.1) = 7.7 \times -4.3 = -33.11$ : (4.5 + 3.2) * (7.8 - 12.1) = -33.11
e. $(4.5 + 3.2) \times |7.8 - 12.1| = 7.7 \times 12.1 = 33.11$ : 4.5 + 3.2 * abs(7.8 - 12.1) = 33.11
Exercise 4
A arithmetic operator that is included in Python which you haven’t used yet in this chapter is the modulo operator (%). This produces the remainder of a division operation. Calculate the following outside of Python and using Python, and then compare the answers:
- $13 \div 10$
- $10 \div 13$
- $7 \div 2$
- $6 \div 2$
a. $13 \% 10 = 13 - 1\times10 = 3$ : 13 % 10 = 3
b. $10 \% 13 = 10 - 0\times13 = 10$ : 10 % 13 = 10
c. $7 \% 2 = 7 - 3\times2 = 1$ : 7 % 2 = 1
d. $6 \% 2 = 6 - 3\times2 = 0$ : 6 % 2 = 0
Exercise 5
A function included in Python that you haven’t yet seen is pow(), which raises one number to the power of another and accepts two positional_arguments and one keyword_argument. Use the help() function to get information on how to use pow(), and then use it to compute the following:
- $2^{3.14}$
- $\sqrt{2}$
- $7^{3/4}$
- A rendering of Avogadro’s number.
To get the help for the pow() function:
>>> help(pow)
Help on built-in function pow in module builtins:
pow(base, exp, mod=None)
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.a.
pow(2, 3.14)
8.815240927012887
b.
pow(2, .5)
1.4142135623730951
c.
pow(7, .75)
4.303517070658851
d.
6.022 * pow(10, 23)
6.0219999999999996e+23
Exercise 6
In Excercise 4, you learned modulo, and in Excercise 5, you learned to use the pow() function. Using the pow() function and modulo operator only, check to see if $7^3$ is a factor of 3.
pow(7,3) % 3
1
There is a remainder of $1$, so it is not.
Exercise 7
Compute the following answers, rounded to the specified number of digits, using the round() function’'.
- $2/3$ rounded to the nearest thousandth.
- $\pi$ rounded to the nearest hundredth.
- $5.6^3.2$ rounded to the nearest tens digit.
- $1/3.3$ rounded to the nearest billionth.
See below:
a. >>> round(2/3, ndigits = 3)
0.667
b. round(3.14159, ndigits = 2)
3.14
c. round(5.6**3.2, ndigits = -1)
250.0
d. round(1/3.3, ndigits = 9)
0.303030303
Clarifying how your code works with comments
Exercise 8
Produce comments for the code you used to solve Exercises 3b, 4a, 5a, and 6.
See below:
3b. Compute the absolute value of 2 - 3 using the abs() function
4a. Compute the remainder of 13 / 10 using the modulo (%) operator
5a. Compute 2 to the power of 5 using the pow() function
Exercise 6
Determine if 7**3 is a power of 3 using the modulo function. If result is 0, it is a power of 3
Temporarily storing data using variables
Exercise 10
Which of the following are valid variable names in Python? For invalid variable names, propose a new name that is acceptable.
2nd_triallength*width^volumedef__hidden_variable_fast component
See below:
a. Invalid - begins with a numeral. Instead, try second_trial.
b. Invalid - contains an operator. Instead, try length_times_width.
c. Invalid - contains a character that is not allowable for variable names. Instead, try uparrow_volume.
d. Invalid - def is a Python reserved keyword. Instead, try the_def.
e. Valid - underscores can be used in an position.
f. Valid - variable names do not have to have letters. In fact, _ is sometimes used for throwaway values.
g. Invalid - variable names can not have spaces. Instead, use underscores, like fast_component.
Exercise 11
Create valid Python variables for the masses of carbon, hydrogen, oxygen, and nitrogen. Then using these variables, compute the molar masses of:
- $\ce{NO2}$
- water
- glucose
- benzene
- pyridine
- glycine
Define the masses as follows:
m_C = 12.011 # g/mol
m_H = 1.008 # g/mol
m_O = 15.999 # g/mol
m_N = 14.007 # g/mola. m_N + 2 * m_O
46.005
b. 2 * m_H + m_O
18.015
c. 6 * m_C + 12 * m_H + 6 * m_O
180.156
d. 6 * m_C + 6 * m_H
78.114
e. 5 * m_C + m_N + 5 * m_H
79.102
f. 2 * m_C + 5 * m_H + m_N + 2 * m_O
75.067
Exercise 11
Using only the mass of hydrogen, carbon, nitrogen, and oxygen, compute the mass of hexaglycine simply by adding up all the masses of the elements.
12 * m_C + 30 * m_H + 6 * m_N + 12 * m_O
450.402
Exercise 12
Solve Exercise 11 and then, without retyping any code, press up until you highlight the line for calculating the mass of a single glycine. Modify this line to store the mass as a variable. Then, use this new variable to calculate the mass of hexaglycine without using the atomic masses directly.
m_glycine = 2 * m_C + 5 * m_H + m_N + 2 * m_O
6 * m_glycine
450.402
Expressing_data_as_readable_text_using_strings
Exercise 13
Enter each of the following into the console and press return, then also put the value inside a print() statement and compare the outputs.
- 2.0
- ‘2.0’
- 2/2
- ‘2/2’
- ’test'
- test
See below:
a. print(2.0)
2.0
b. print('2.0')
2.0
c. print(2/2)
1.0
d. print('2/2')
2/2
e. print(test)
.
NameError: name 'test' is not defined
Cell In[34], line 1
----> 1 print(test)f. print('test')
test
Exercise 14
Using a single line of code with a single print command, output a grammatically correct sentence that answers the following questions (perform the math, if necessary, and output with correct units):
- What is the number of moles of water in 14.7g of water?
- How many mL are in 1.35 gallons?
- What is 72.5 $^{\circ}$F in $^\circ$C?
See below:
a. print('There are', 14.7 / (2 * m_H + m_O), 'moles of water in 14.7 g of water.')
There are 0.8159866777685262 moles of water in 14.7 g of water.
b. print('There are', 1.35 * 3785.41, 'mL in a gallon.')
There are 5110.3035 mL in a gallon.
c. print('72.5 degrees Fahrenheit is', (72.5-32) * 5 / 9, 'degrees Celsius.')
72.5 degrees Fahrenheit is 22.5 degrees Celsius.
Avoiding repetitive typing by making your own functions
Exercise 15
Create functions that do the following tasks:
- Print the number of moles of water for a given mass of water. Here, the mass of water should be a positional_argument. Confirm that your function works by reproducing the result of Exercise 14a.
- Convert a temperature in degrees Fahrenheit to degrees Celsius and print the result. Confirm that your function works by reproducing the result of Exercise 14c.
- Solve dilution problems ($M_1V_1 = M_2V_2$) for $M_1$. Show two examples that prove that it works correctly.
- Solve dilution problems ($M_1V_1 = M_2V_2$) for $V_1$. Show two examples that prove that it works correctly.
See below:
a.
def calcMolesWater(m_water):
print(m_water / 18.015, 'moles of water')
calcMolesWater(14.7)Which will output:
0.8159866777685262 moles of water
.
b.
def convertToCelsius(T_F):
print((T_F - 32) * 5 / 9, 'degrees Celsius')
convertToCelsius(72.5)Which will output:
22.5 degrees Celsius
c.
def diluteConc(M2, V1, V2):
print(M2, 'M diluted from', V1, 'to', V2, 'is', M2 * V2 / V1, 'M.')
diluteConc(.1, 1, 0.01)which will output:
0.1 M diluted from 1 to 0.01 is 0.001 M.
d.
def diluteVol(M1, M2, V2):
print('To dilute', M1, 'M to', M2, 'M, with a final volume of', V2, 'L, you need', M2 * V2 / M1, 'L.')
diluteVol(.1, .001, 1)which will output:
To dilute 0.1 M to 0.001 M, with a final volume of 1 L, you need 0.01 L.
Exercise 16
Write a function that will take two masses of samples of water and compute the difference in the number of molecules of water of the two samples, but rounded to the nearest thousandth of a mole. Write your function so that the order of masses supplied as arguments to the function does not matter.
def waterDiff(m1, m2):
moles_diff = abs(m1 - m2) / 18.015
molecules_diff = round(moles_diff, 3) * 6.022 * 10**23
print('The difference in number of molecules of water is', molecules_diff)
`waterDiff(1, .9)`which will output:
The difference in number of molecules of water is 3.6132e+21
Exercise 18
You have a spectroscopic detector that you need to cool to 6 K using liquid He. You know the heat capacity of the detector is $105 J kg^{-1} K^{-1}$. Write a function that will take the current (room) temperature of the detector and print the number of liters of liquid He it will take to cool down the detector, rounded to the nearest tenth of a liter. Assume that it requires 5L to simply cool down the transfer line, before you start cooling the detector. Also, print a statement that converts the function’s output to a cost in dollars to cool down the detector, rounded to the nearest dollar. At the time of this writing, the cost of liquid helium is $40/L. Make this the default value, but write the function so that the user can specify any price.
def costCoolDet(price_lHe = 40):
# Compute the heat change required given the heat capacity of the detector is 105 J/K
Q = 125 / (298 - 6) # J
# Now determine the mass of helium that must boil to absorb this heat, given a latent heat of 20.5 J/g
m_He = Q / 20.5 # g
# Calculate the volume of helium that evaporates, given a density of 125 g/L
V_He = m_He / 125 + 5
print(round(V_He,1), 'L of helium evaporates.')
cost_He = V_He * price_lHe
print('This costs', round(cost_He), 'dollars.')
costCoolDet()Which will output:
5.0 L of helium evaporates.
This costs 200 dollars.