0% found this document useful (0 votes)
65 views17 pages

#Imported Modules Tclass1 Acid Tclass2 Base Tmod T Math Random

This document contains code for a virtual acid-base titration simulation. It allows the user to choose between a random or specific acid/base, calculates the equivalent volume needed for the titration, and walks the user through checking the pH at three checkpoints: before, at, and after the equivalence point. The program uses classes and functions to model the chemical reaction and indicator color changes during the titration process.

Uploaded by

api-483033170
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views17 pages

#Imported Modules Tclass1 Acid Tclass2 Base Tmod T Math Random

This document contains code for a virtual acid-base titration simulation. It allows the user to choose between a random or specific acid/base, calculates the equivalent volume needed for the titration, and walks the user through checking the pH at three checkpoints: before, at, and after the equivalence point. The program uses classes and functions to model the chemical reaction and indicator color changes during the titration process.

Uploaded by

api-483033170
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

'''

Ashley Hong
cs50AP spring project
3 May 2019
'''
#imported modules
from tclass1 import Acid
from tclass2 import Base
import tmod as t
import math
import random

def main():
#introduction page for titration
print("WELCOME to the Virtual Acid/Base titration lab.")
print("With the use of this program, You can create a simulation of the
lab before attempting the actual lab.")

#printing definition of terms for user


print("First let's choose the whether the acid or base is the
titrant/analyte.")
def1 = input("Would you like a definition of each (y/n):")
#if the user wants definitions
if(def1 == 'y'):
print("Analyte: a substance whose chemical constituents are being
identified and measured.")
print("Titrant: a solution of known concentration that is added
(titrated) to another solution to determine the concentration of the
analyte.")
print("\n")
#takes in the analyte and titrant
analyte = input("Analyte (acid or base):")
#takes in titrant
titrant = input("Titrant (acid or base):")
else:
# if the user does not need definitions
print("\n")
analyte = input("Analyte (acid or base):")
titrant = input("Titrant (acid or base):")

#transition
print("The next step is choosing the actual acid and base from the list
provided.")
#list of acid and base
strongacid = ['HCL', 'HBR', 'HI']
strongbase = ['KOH', 'LIOH', 'NAOH']

print("\n")
#gives user random option
choice = input("Would you like a random option (y/n):")
if(choice == 'y'):
#choice procedure
t.choice()
else:
print("\n")
#gives acid list
print(strongacid)
#name of acid
aname = input("Enter the chosen Acid:")
if(aname.upper() in strongacid):
#user guide
print(" TIP: The usual concentration for a strong acid is
(.01 -.9)")
acon = float(input("Enter the concentration for the Acid:"))
else:
print("Please Enter the correct acid from the list.")
#if incorrect acid listed, returns 1
print("Try again")
return 1
acid = Acid(aname, acon)
#class for acid to print name adn concentration
acid.printAcid()

print("\n")
#prints base list
print(strongbase)
#name of base
bname = input("Enter the chosen Base:")
if(bname.upper() in strongbase):
print(" TIP: The usual concentration for a strong base is
(.01 -.9)")
bcon = float(input("Enter the concentration for the Base:"))
else:
print("Please enter the correct base fromt the list")
#returns 1 if name not in list
print("Try again")
return 1
base = Base(bname, bcon)
#class for base name and concentration
base.printBase()

for x in range(2):
print("\n")
print("Now with the given input, let's create the chemical reaction for
this titration.")
#creating chemical reaction equasion
t.equationstrong()

print("Now Let's start the titration pre-calculations.")


print("\n")

#for the random choice


if(choice == 'y'):
#volume of analyte neded
anvol = float(input("How many mililiters of analyte will you
use:"))
#concentration of chosen acid
acon1 = float(input("Concentration for the acid:"))
#concentraion of chosen base
bcon1 = float(input("Concentration for the base:"))
#uses concentration of both to find equilibrium volume
total = t.equil(acon1, bcon1)
#for the lambda function in the equilibrium function
d = total(anvol)
#prints the total volume
print("For this equasion, {} mililiters of the titrant will be
used".format(round((d * 1000),2)))
print("\n")
else:
#if the user does not randomyl choose the acid or base
anvol = float(input("How many mililiters of analyte will you
use:"))
#uses the equilibrium function
total = t.equil(acon, bcon)
d = total(anvol)
print("For this equasion, {} mililiters of the titrant will be
used".format(round((d * 1000),2)))
print("\n")

#list of two indicators for this reaction


#gives user a choice
indicators = ['Methyl Red (red)', 'Bromothymol Blue (blue)']
#prints list
print(indicators)
#choosing the indicator
ind = int(input("Choose an Indicator (1/2):"))
#decreases by one to accound for zero
print("You have chose the indicator:", indicators[ind - 1])

#printing procedure in list


print("\n")
print("Procedure.")
print(" 1. In this simulator, the Raspberry Pi will flash a specific
color based on the indicator chosen")
print(" 2. Then it will hold the indicator's original color as the
titration continues")
print(" 3. When the titration has reached the equivalence point the
color solution will hold the opposite indicator's color for 10 seconds")
print(" 4. When the titration passes the equivalence point, the
raspberry Pi will flash the original color.")
print("\n")
print("There are 3 checkpoints where you must find the PH of the
solution.")
x = [" 1. Before the titration", " 2. At the equivalence point",
" 3. After the equivalence point"]
print('\n'.join(x))

print("Now that we have prepared the theoretical volume, let's begin


actual titration")
print("At the beginning of the titration the Ph of the solution is:")

#for the random acid or base


if(choice == 'y'):
#sets volume to zero at beginning of reaction
tivol1 = 0
if(analyte.lower() == 'acid'):
#indicator procedure
t.indicator(ind)
#finding the pH of acid
y = t.ph(acon1, anvol, bcon1, tivol1, analyte)
print(y)
elif(analyte.lower() == 'base'):
#indicator procedure
t.indicator(ind)
#finding pH of base
x = t.ph(bcon1,anvol, acon1, tivol1, analyte)
print(x)
#prints user guide for adding volume
print("Until {} mL, add ____ mL and watch the pH change/indicator
change".format(round((d*1000),2)))
#while loop under needed value
while(tivol1 < round((d*1000),2)):
#adding the volume
tivol2 = float(input("Add titrant(mL):"))
#incrementing with the addition of volume
tivol1 = tivol1 + tivol2
print(tivol1)
#when the equivalence volume is reached, procede
if(tivol1 == round((d*1000),2)):
if(analyte.lower() == 'acid'):
#indicator procedure
t.indicator(ind)
#pH for the equivalence point
y = t.ph(acon1, anvol, bcon1, tivol1, analyte)
print(y)
elif(analyte.lower() == 'base'):
#indicator procedure
t.indicator(ind)
#pH for the equivalence point
x = t.ph(bcon1,anvol, acon1, tivol1, analyte)
print(x)
print("We will check the pH past the equivalence point.")
print("Choose a volume that is greater than {} and less than
{}".format(round((d*1000),2), round((d*2*1000),2)))
#finding the volume past the equivalence point
tivol3 = float(input("Add titrant past equivalence point(mL):"))
if(analyte.lower() == 'acid'):
#indicator procedure
t.indicator(ind)
#pH calculation function passing equivalence point
y = t.ph(acon1, anvol, bcon1, tivol3, analyte)
print(y)
elif(analyte.lower() == 'base'):
#indicator procedure
t.indicator(ind)
#pH calculation function passing equivalence point
x = t.ph(bcon1,anvol, acon1, tivol3, analyte)
print(x)

#repeating process for individually chosen acid and base


else:
tivol1 = 0
if(analyte.lower() == 'acid'):
#indicator procedure
t.indicator(ind)
#ph for acid
y = t.ph(acon, anvol, bcon, tivol1, analyte)
print(y)
elif(analyte.lower() == 'base'):
#indicator procedure
t.indicator(ind)
#finding pH of base
x = t.ph(bcon,anvol, acon, tivol1, analyte)
print(x)
print("Until {} mL, add ____ mL and watch the pH change/indicator
change".format(round((d*1000),2)))
#while loop under needed value
while(tivol1 < round((d*1000),2)):
tivol2 = float(input("Add titrant(mL):"))
#incrementing with the addition of volume
tivol1 = tivol1 + tivol2
print(tivol1)
if(tivol1 == round((d*1000),2)):
if(analyte.lower() == 'acid'):
#indicator procedure
t.indicator(ind)
#pH at equivalence point
y = t.ph(acon, anvol, bcon, tivol1, analyte)
print(y)
elif(analyte.lower() == 'base'):
#indicator procedure
t.indicator(ind)
#finding pH of base at equivalence point
x = t.ph(bcon,anvol, acon, tivol1, analyte)
print(x)
print("We will check the pH past the equivalence point.")
print("Choose a volume that is greater than {} and less than
{}".format(round((d*1000),2), round((d*2*1000),2)))
tivol3 = float(input("Add titrant past equivalence point(mL):"))
if(analyte.lower() == 'acid'):
#indicator procedure
t.indicator(ind)
#pH calculation function passing equivalence point
y = t.ph(acon, anvol, bcon, tivol3, analyte)
print(y)
elif(analyte.lower() == 'base'):
#indicator procedure
t.indicator(ind)
#pH calculation function passing equivalence point
x = t.ph(bcon,anvol, acon, tivol3, analyte)
print(x)

#conclusion
print("\n")
print("We have now successfully completed the Titration Simulator.")
print("Now apply this knowledge to be able to apply it to a real
experiment.")
print("Thank you for your time")

#main format
if( __name__ ) == "__main__":
main()
'''
Ashley Hong
cs50AP spring mod
3 May 2019
'''

#import RPi.GPIO as GPIO


import time
import random
import re
import math

#procedures
def choice():
#list of strong acid and base
strongacid = ['HCL', 'HBR', 'HI']
strongbase = ['KOH', 'LIOH', 'NAOH']
#chooses a raondom int with python function
x = random.randint(0,2)
#chooses random acid with chosennuber
acid = strongacid[x]
#user guide
print(" TIP: The usual concentration for a strong acid is (.01 -.9)")
#finds concentration of acid with user input
acon = float(input("Enter a concentration for the acid:"))
#chooses another random integer
y = random.randint(0,2)
print(" TIP: The usual concentration for a strong base is (.01 -.9)")
#concentration of base with user input
bcon = float(input("Enter a concentration for the base:"))
#chooses strong base from list
base = strongbase[y]
#prints chosen values
print("For this reaction, {} was chosen with {} M
concentration.".format(acid, acon))
print("For this reaction, {} was chosen with {} M
concentration.".format(base, bcon))

def equationstrong():
#prints the chemical reactions
print("For the titration, we will create the chemical reaction.")
print("Please re-enter the chosen acid and base.")

#finds acid name chosen


acidname = input("Re-enter the acid you chose:")
#uses re to subsitute the letters
#this is used to get rid of H in acid names to create ions
acidname3 = re.sub('H', '', acidname.upper())
#user input base names
basename = input("Re-enter the base you chose:")
#use re (python function) to subsitute letters
#gets rid of OH to create ions
basename3 = re.sub('OH', '', basename.upper())

print("\n")
print("The chemcial reaction is:")
#uses format (python function) to print compounds and their formula
print("{} + {} = {}{} + H2O ".format(acidname.upper() ,basename.upper(),
basename3.upper(), acidname3.upper()))
print("\n")

def indicator(x):
#raspberry pi component
red = 7
blue = 13
#for first indicator
if(x == 1):
step = input("Is it BEFORE/AT/AFTER the equivalence point:")
# it is first step
if(step.lower() == "before"):
#GPIO settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(red, GPIO.OUT)
#turn LED on
print("led on")
GPIO.output(red, GPIO.OUT)
#hod for five seconds
time.sleep(5)
print("led off")
#turn LEF off
GPIO.output(red, GPIO.LOW)
time.sleep(.5)
#at equivalence point
elif(step.lower() == "at"):
#GPIO settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(blue, GPIO.OUT)
#LED on
print("led on")
GPIO.output(blue, GPIO.OUT)
time.sleep(5)
print("led off")
#LED off
GPIO.output(blue, GPIO.LOW)
time.sleep(.5)
#passing equivalence point
elif(step.lower() == "after"):
#GPIO settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(red, GPIO.OUT)
print("led on")
GPIO.output(red, GPIO.OUT)
time.sleep(5)
print("led off")
GPIO.output(red, GPIO.LOW)
time.sleep(.5)

#if 2nd indicator is chosen


elif(x == 2):
step = input("Is it BEFORE/AT/AFTER the equivalence point:")
#before reaction
if(step.lower() == "before"):
#GPIO settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(blue, GPIO.OUT)
#LED on
print("led on")
GPIO.output(blue, GPIO.OUT)
time.sleep(5)
#LED off
print("led off")
GPIO.output(blue, GPIO.LOW)
time.sleep(.5)
#at equivalence point
elif(step.lower() == "at"):
#GPIO settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(red, GPIO.OUT)
#LED on
print("led on")
GPIO.output(red, GPIO.OUT)
time.sleep(5)
#LED off
print("led off")
GPIO.output(red, GPIO.LOW)
time.sleep(.5)
#passing the point
elif(step.lower() == "after"):
#GPIO settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(blue, GPIO.OUT)
#LED on
print("led on")
GPIO.output(blue, GPIO.OUT)
time.sleep(5)
#LED off
print("led off")
GPIO.output(blue, GPIO.LOW)
time.sleep(.5)

#functions
def equil(y,z):
#equivalence point volume
#introduction
print("For the first step, You must choose the volume of the analyte
being used.")
print("Now that we have chosen the analyte volume we will use the
titration formula to find the Equivalence point")
#with the given analyte
analyte = input("What is the analyte (acid or base):")
print("\n")
#if the analyte is an acid
if(analyte.lower() == "acid"):
#simplify code using lambda function
#returns found equilibrium volume
return lambda x: ((x/1000) * y / z )
#if the analyte is a base
elif(analyte.lower() == "base"):
#simplify with lambda function
3#returns equilibiurm volume
return lambda x: ((x/1000) * z / y)

#a = acid concen
#b = acid volume
#c = base concen
#d = titrant volume
#e = analyte
def ph(a,b,c,d,e):
#calculating the pH of solutions
step = int(input("What step of the titration is this (1/2/3):"))
#step one
if(step == 1):
#uses round (python function) to return rounded result
# log to find pH
if(e == "acid"):
print("The pH is:")
return round((-math.log(a,10)),3)
if(e == "base"):
print("The pH is:")
return round((14 -(-math.log(a,10))),3)
#step 2
elif(step == 2):
#moles of analyte and titrant
anmoles = (b/1000) * a
timoles = (d/1000) * c
molarity = (anmoles - timoles) + (1.0*10**-7)
#uses round (python function) to return rounded result
#log to find pH
if(e == "acid"):
print("The pH is:")
return round((- math.log(molarity,10)),3)
if(e == "base"):
print("The pH is:")
return round((- math.log(molarity,10)),3)
#step 3
elif(step == 3):
#moles of analyte
anmoles = (b/1000) * a
timoles = (d/1000) * c
#moles of base
oh = timoles - anmoles
#molarity
molarity2 = oh/(b + d)
poh = (- math.log(molarity2,10))
#uses round (python function) to return rounded result
#log to find pH
if(e == "acid"):
print("The pH is:")
return round((14 - poh),3)
if(e == "base"):
print("The pH is:")
return round((poh),3)
'''
Ashley Hong
cs50AP spring class1
3 May 2019
'''
#ACID class
#create class for acid
class Acid():
#first field for acid name
acidname = ""
#next field for acid concentration
acidconcentration = 0

#creating the class


def __init__(self, acid, concentration):
#setting the correct fields
self.acidname = acid
self.acidconcentration = concentration

#two getters
def getAcidName(self):
#return the self.acidname
return self.acidname

def getAcidConcentration(self):
#return the self.acidconcentration
return self.acidconcentration

#two setters
def setAcidName(self, acid):
self.acidname = acid

def setAcidConcentration(self, concentration):


self.acidconcentration = concentration

def printAcid(self):
#displays fields to user, statement for user to show the chosen acid
and concentration
#uses format (python function)
print("For this reaction, {} was chosen with {} M
concentration.".format(self.getAcidName() , self.getAcidConcentration()))
'''
Ashley Hong
cs50AP spring class2
3 May 2019
'''
#BASE calss
#creating class for base
class Base():
#first field
#base name field
basename = ""
#next field
#field for base concentration
baseconcentration = 0

#creating class for choosing base and concentration


def __init__(self, base, concentration):
self.basename = base
self.baseconcentration = concentration

#two getters
def getBaseName(self):
return self.basename

def getBaseConcentration(self):
return self.baseconcentration

#two setters
def setBaseName(self, base):
self.basename = base

def setBaseConcentration(self, concentration):


self.baseconcentration = concentration

def printBase(self):
#user displayed statement showing two fields and the chosen name and
concentration
#uses format (python function)
print("For this reaction, {} was chosen with {} M
concentration.".format(self.getBaseName() , self.getBaseConcentration()))
~/workspace/spring/ $ python titration.py
WELCOME to the Virtual Acid/Base titration lab.
With the use of this program, You can create a simulation of the lab before
attempting the actual lab.
First let's choose the whether the acid or base is the titrant/analyte.
Would you like a definition of each (y/n):n

Analyte (acid or base):base


Titrant (acid or base):acid
The next step is choosing the actual acid and base from the list provided.

Would you like a random option (y/n):n

['HCL', 'HBR', 'HI']


Enter the chosen Acid:hbr
TIP: The usual concentration for a strong acid is (.01 -.9)
Enter the concentration for the Acid:.01
For this reaction, hbr was chosen with 0.01 M concentration.

['KOH', 'LIOH', 'NAOH']


Enter the chosen Base:naoh
TIP: The usual concentration for a strong base is (.01 -.9)
Enter the concentration for the Base:.02
For this reaction, naoh was chosen with 0.02 M concentration.

Now with the given input, let's create the chemical reaction for this
titration.
For the titration, we will create the chemical reaction.
Please re-enter the chosen acid and base.
Re-enter the acid you chose:hbr
Re-enter the base you chose:naoh

The chemcial reaction is:


HBR + NAOH = NABR + H2O

Now Let's start the titration pre-calculations.

How many mililiters of analyte will you use:100


For the first step, You must choose the volume of the analyte being used.
Now that we have chosen the analyte volume we will use the titration
formula to find the Equivalence point
What is the analyte (acid or base):base

For this equasion, 200.0 mililiters of the titrant will be used

['Methyl Red (red)', 'Bromothymol Blue (blue)']


Choose an Indicator (1/2):2
You have chose the indicator: Bromothymol Blue (blue)
Procedure.
1. In this simulator, the Raspberry Pi will flash a specific color
based on the indicator chosen
2. Then it will hold the indicator's original color as the titration
continues
3. When the titration has reached the equivalence point the color
solution will hold the opposite indicator's color for 10 seconds
4. When the titration passes the equivalence point, the raspberry Pi
will flash the original color.

There are 3 checkpoints where you must find the PH of the solution.
1. Before the titration
2. At the equivalence point
3. After the equivalence point
Now that we have prepared the theoretical volume, let's begin actual
titration
At the beginning of the titration the Ph of the solution is:
Is it BEFORE/AT/AFTER the equivalence point:before
#look at video
led on
led off
What step of the titration is this (1/2/3):1
The pH is:
12.301
Until 200.0 mL, add ____ mL and watch the pH change/indicator change
Add titrant(mL):100
100.0
Add titrant(mL):100
200.0
Is it BEFORE/AT/AFTER the equivalence point:at
#look at video
led on
led off
What step of the titration is this (1/2/3):2
The pH is:
7.0
We will check the pH past the equivalence point.
Choose a volume that is greater than 200.0 and less than 400.0
Add titrant past equivalence point(mL):300
Is it BEFORE/AT/AFTER the equivalence point:after
#look at video
led on
led off
What step of the titration is this (1/2/3):3
The pH is:
5.602

We have now successfully compelted the Titration Simulator.


Now apply this knowledge to be able to apply it to a real experiment.
Thank you for your time
#SECOND RUN - ACID
~/workspace/spring/ $ python titration.py
WELCOME to the Virtual Acid/Base titration lab.
With the use of this program, You can create a simulation of the lab before
attempting the actual lab.
First let's choose the whether the acid or base is the titrant/analyte.
Would you like a definition of each (y/n):y
Analye: a substance whose chemical constituents are being identified and
measured.
Titrant: a solution of known concentration that is added (titrated) to
another solution to determine the concentration of the analyte.

Analyte (acid or base):acid


Titrant (acid or base):base
The next step is choosing the actual acid and base from the list provided.

Would you like a random option (y/n):y


TIP: The usual concentration for a strong acid is (.01 -.9)
Enter a concentration for the acid:.05
TIP: The usual concentration for a strong base is (.01 -.9)
Enter a concentration for the base:.07
For this reaction, HCL was chosen with 0.05 M concentration.
For this reaction, LIOH was chosen with 0.07 M concentration.

Now with the given input, let's create the chemical reaction for this
titration.
For the titration, we will create the chemical reaction.
Please re-enter the chosen acid and base.
Re-enter the acid you chose:HCL
Re-enter the base you chose:LIOH

The chemcial reaction is:


HCL + LIOH = LICL + H2O

Now Let's start the titration pre-calculations.

How many mililiters of analyte will you use:120


Concentration for the acid:.05
Concentration for the base:.07
For the first step, You must choose the volume of the analyte being used.
Now that we have chosen the analyte volume we will use the titration
formula to find the Equivalence point
What is the analyte (acid or base):acid

For this equasion, 85.71 mililiters of the titrant will be used

['Methyl Red (red)', 'Bromothymol Blue (blue)']


Choose an Indicator (1/2):1
You have chose the indicator: Methyl Red (red)
Procedure.
1. In this simulator, the Raspberry Pi will flash a specific color
based on the indicator chosen
2. Then it will hold the indicator's original color as the titration
continues
3. When the titration has reached the equivalence point the color
solution will hold the opposite indicator's color for 10 seconds
4. When the titration passes the equivalence point, the raspberry Pi
will flash the original color.

There are 3 checkpoints where you must find the PH of the solution.
1. Before the titration
2. At the equivalence point
3. After the equivalence point
Now that we have prepared the theoretical volume, let's begin actual
titration
At the beginning of the titration the Ph of the solution is:
Is it BEFORE/AT/AFTER the equivalence point:before
#look at video
led on
led off
What step of the titration is this (1/2/3):1
The pH is:
1.301
Until 85.71 mL, add ____ mL and watch the pH change/indicator change
Add titrant(mL):10
10.0
Add titrant(mL):20
30.0
Add titrant(mL):30
60.0
Add titrant(mL):20
80.0
Add titrant(mL):5.71
85.71
Is it BEFORE/AT/AFTER the equivalence point:at
#look at video
led on
led off
What step of the titration is this (1/2/3):2
The pH is:
6.398
We will check the pH past the equivalence point.
Choose a volume that is greater than 85.71 and less than 171.43
Add titrant past equivalence point(mL):115
Is it BEFORE/AT/AFTER the equivalence point:after
#look at video
led on
led off
What step of the titration is this (1/2/3):3
The pH is:
8.941

We have now successfully compelted the Titration Simulator.


Now apply this knowledge to be able to apply it to a real experiment.
Thank you for your time

You might also like