无编辑摘要
无编辑摘要
 
(未显示另一用户的1个中间版本)
第1行: 第1行:
<code><nowiki>#</nowiki> A dictionary of some common elements and their relative atomic masses</code>
<pre>#A dictionary of some common elements and their relative atomic masses


<code>elements = {"H": 1.008, "He": 4.003, "Li": 6.941, "Be": 9.012,</code>
elements = {'H': 1.008, 'He': 4.003, 'Li': 6.941, 'Be': 9.012,  


<code>            "B": 10.81, "C": 12.01, "N": 14.01, "O": 16.00,</code>
            'B': 10.81, 'C': 12.01, 'N': 14.01, 'O': 16.00,  


<code>            "F": 19.00, "Ne": 20.18, "Na": 22.99, "Mg": 24.31,</code>
            'F': 19.00, 'Ne': 20.18, 'Na': 22.99, 'Mg': 24.31,  


<code>            "Al": 26.98, "Si": 28.09, "P": 30.97, "S": 32.07,</code>
            'Al': 26.98, 'Si': 28.09, 'P': 30.97, 'S': 32.07,  


<code>            "Cl": 35.45, "Ar": 39.95, "K": 39.10 , "Ca" :40.08 ,</code>
            'Cl': 35.45, 'K': 39.10, 'Ar': 39.95, 'Ca': 40.08,  


<code>            'Sc':44.96 , 'Ti':47.87 , 'V':50.94 , 'Cr':52.00 ,</code>
            'Sc': 44.96, 'Ti': 47.87, 'V': 50.94, 'Cr': 52.00,  


<code>            'Mn':54.94 , 'Fe':55.85 , 'Co':58.93 , 'Ni':58.69 ,</code>
            'Mn': 54.94, 'Fe': 55.85, 'Ni': 58.69, 'Co': 58.93,  


<code>            'Cu':63.55 , 'Zn':65.38 , 'Ga':69.72 , 'Ge':72.63 ,</code>
            'Cu': 63.55, 'Zn': 65.38, 'Ga': 69.72, 'Ge': 72.63,  


<code>            'As':74.92 , 'Se':78.97 , 'Br':79.90 , 'Kr' :83.80 ,</code>
            'As': 74.92, 'Se': 78.96, 'Br': 79.90, 'Kr': 83.80,  


<code>            'Rb' :85.47 ,'Sr' :87.62,'Y' :88.91,'Zr':91.22,</code>
            'Rb': 85.47, 'Sr': 87.62, 'Y': 88.91, 'Zr': 91.22,  


<code>            'Nb' :92.91,'Mo' :95.95,'Tc' :98 ,'Ru' :101.07,</code>
            'Nb': 92.91, 'Mo': 95.94, 'Tc': 98.00, 'Ru': 101.1,  


<code>            'Rh' :102.91,'Pd' :106.42,'Ag' :107.87,'Cd' :112.41,</code>
            'Rh': 102.9, 'Pd': 106.4, 'Ag': 107.9, 'Cd': 112.4,  


<code>            'In' :114.82,'Sn' :118.71,'Sb' :121.76,'Te' :127.60,</code>
            'In': 114.8, 'Sn': 118.7, 'Sb': 121.8, 'I': 126.9,  


<code>            'I':126.90,'Xe':131.29,'Cs':132.91,'Ba':137.33,</code>
            'Te': 127.6, 'Xe': 131.3, 'Cs': 132.9, 'Ba': 137.3,  


<code>            'Hf':178.49,'Ta':180.95,'W':183.84,</code>
            'La': 138.9, 'Ce': 140.1, 'Pr': 140.9, 'Nd': 144.2,  


<code>            'Ir':192.22,'Pt':195.08,'Au':196.97,</code>
            'Pm': 145.0, 'Sm': 150.4, 'Eu': 152.0, 'Gd': 157.3,  


<code>            'Pb':207.2,'Bi':208.98}</code>
            'Tb': 158.9, 'Dy': 162.5, 'Ho': 164.9, 'Er': 167.3,


<code><nowiki>#</nowiki> A function to calculate the relative molecular mass of a chemical formula</code>
            'Tm': 168.9, 'Yb': 173.0, 'Lu': 175.0, 'Hf': 178.5,


<code>def calculate_rmm(formula):</code>
            'Ta': 180.9, 'W': 183.8, 'Re': 186.2, 'Os': 190.2,


<code>    # Initialize the result to zero</code>
            'Ir': 192.2, 'Pt': 195.1, 'Au': 197.0, 'Hg': 200.6,


<code>    result = 0</code>
            'Tl': 204.4, 'Pb': 207.2, 'Bi': 208.9, 'Th': 232.0,


<code>    # Initialize an empty string to store the current element symbol</code>
            'Pa': 231.0, 'U': 238.0, 'Np': 237.0, 'Pu': 244.0,


<code>    element = ""</code>
            'Am': 243.0, 'Cm': 247.0, 'Bk': 247.0, 'Cf': 251.0,


<code>    # Initialize an empty string to store the current number of atoms</code>
            'Es': 252.0, 'Fm': 257.0, 'Md': 258.0, 'No': 259.0,


<code>    number = ""</code>
            'Lr': 262.0, 'Rf': 267.0, 'Db': 270.0, 'Sg': 271.0,


<code>    # Initialize an empty list to store the stack of parentheses</code>
            'Bh': 270.0, 'Hs': 277.0, 'Mt': 276.0, 'Ds': 281.0,


<code>    stack = []</code>
            'Rg': 280.0, 'Cn': 285.0, 'Nh': 284.0, 'Fl': 289.0,


<code>    # Loop through each character in the formula</code>
            'Mc': 288.0, 'Lv': 293.0}


<code>    for char in formula:</code>
<nowiki>#</nowiki> A function to calculate the relative molecular mass of a chemical formula


<code>        # If the character is an uppercase letter</code>
def calculate_rmm(formula):


<code>        if char.isupper():</code>
    # Initialize the result to zero


<code>            # If there is a previous element symbol</code>
    result = 0


<code>            if element:</code>
    # Initialize an empty string to store the current element symbol


<code>                # If there is a previous number of atoms</code>
    element = ""


<code>                if number:</code>
    # Initialize an empty string to store the current number of atoms


<code>                    # Convert the number to an integer and multiply it by the relative atomic mass of the element</code>
    number = ""


<code>                    value = int(number) * elements[element]</code>
    # Initialize an empty list to store the stack of parentheses


<code>                else:</code>
    stack = []


<code>                    # Otherwise assume the number is one and multiply it by the relative atomic mass of the element</code>
    # Loop through each character in the formula


<code>                    value = elements[element]</code>
    for char in formula:


<code>                # If there is a stack of parentheses</code>
        # If the character is an uppercase letter


<code>                if stack:</code>
        if char.isupper():


<code>                    # Append the value to the stack</code>
            # If there is a previous element symbol


<code>                    stack.append(value)</code>
            if element:


<code>                else:</code>
                # If there is a previous number of atoms


<code>                    # Otherwise add it to the result</code>
                if number:


<code>                    result += value</code>
                    # Convert the number to an integer and multiply it by the relative atomic mass of the element


<code>                # Reset the number to an empty string</code>
                    value = int(number) * elements[element]


<code>                number = ""</code>
                else:


<code>            # Set the current element symbol to the character</code>
                    # Otherwise assume the number is one and multiply it by the relative atomic mass of the element


<code>            element = char</code>
                    value = elements[element]


<code>        # If the character is a lowercase letter</code>
                # If there is a stack of parentheses


<code>        elif char.islower():</code>
                if stack:  


<code>            # Append it to the current element symbol</code>
                    # Append the value to the stack


<code>            element += char  </code>
                    stack.append(value)


<code>        elif char.isdigit():  </code>
                else:  


<code>            number += char  </code>
                    # Otherwise add it to the result


<code>        elif char == "(":</code>
                    result += value


<code>            if element:  </code>
                # Reset the number to an empty string


<code>                if number:  </code>
                number = ""


<code>                    value = int(number) * elements[element]  </code>
            # Set the current element symbol to the character


<code>                else:  </code>
            element = char


<code>                    value = elements[element]  </code>
        # If the character is a lowercase letter


<code>                if stack:  </code>
        elif char.islower():  


<code>                    stack.append(value)  </code>
            # Append it to the current element symbol


<code>                else:  </code>
            element += char  


<code>                    result += value  </code>
        elif char.isdigit():  


<code>                element = ""  </code>
            number += char  


<code>                number = ""  </code>
        elif char == "(":


<code>            stack.append(char)  </code>
            if element:  


<code>        elif char == ")":</code>
                if number:  


<code>            if element:</code>
                    value = int(number) * elements[element]  


<code>                if number:</code>
                else:  


<code>                    value = int(number) * elements[element]</code>
                    value = elements[element]  


<code>                else:</code>
                if stack:  


<code>                    value = elements[element]</code>
                    stack.append(value)  


<code>                if stack:</code>
                else:  


<code>                    stack.append(value)</code>
                    result += value   


<code>                else:</code>
                element = ""   


<code>                    result += value</code>
                number = ""   


<code>            element = ""</code>
            stack.append(char)   


<code>            number = ""</code>
        elif char == ")":


<code>            # Pop the values from the stack until reaching a left parenthesis</code>
            if element:


<code>            temp_result = 0</code>
                if number:


<code>            while stack and stack[-1] != "(":</code>
                    value = int(number) * elements[element]


<code>                temp_result += stack.pop()</code>
                else:


<code>            # Pop the left parenthesis from the stack</code>
                    value = elements[element]


<code>            if stack and stack[-1] == "(":</code>
                if stack:


<code>                stack.pop()</code>
                    stack.append(value)


<code>            # Check if there is a number after the right parenthesis</code>
                else:


<code>            i = formula.index(char) + 1</code>
                    result += value


<code>            if i < len(formula) and formula[i].isdigit():</code>
            element = ""


<code>                # Multiply the temporary result by the number and append it to the stack or add it to the result</code>
            number = ""


<code>                temp_result *= int(formula[i])</code>
            # Pop the values from the stack until reaching a left parenthesis


<code>                if stack:</code>
            temp_result = 0


<code>                    stack.append(temp_result)</code>
            while stack and stack[-1] != "(":


<code>                else:</code>
                temp_result += stack.pop()


<code>                    result += temp_result</code>
            # Pop the left parenthesis from the stack


<code>                # Skip the next character as it is already processed</code>
            if stack and stack[-1] == "(":


<code>                continue</code>
                stack.pop()


<code>            else:</code>
            # Check if there is a number after the right parenthesis


<code>                # Otherwise append the temporary result to the stack or add it to the result as it is</code>
            i = formula.index(char) + 1


<code>                if stack:</code>
            if i < len(formula) and formula[i].isdigit():


<code>                    stack.append(temp_result)</code>
                # Multiply the temporary result by the number and append it to the stack or add it to the result


<code>                else:</code>
                temp_result *= int(formula[i])


<code>                    result += temp_result</code>
                if stack:


<code>    # Check if there is a remaining element and number at the end of the formula and add them to the result        </code>
                    stack.append(temp_result)


<code>    if element:  </code>
                else:


<code>        if number:  </code>
                    result += temp_result


<code>            value = int(number) * elements[element]  </code>
                # Skip the next character as it is already processed


<code>        else:  </code>
                continue


<code>            value = elements[element]  </code>
            else:


<code>        result += value  </code>
                # Otherwise append the temporary result to the stack or add it to the result as it is


<code>    return result</code>
                if stack:


<code><nowiki>#</nowiki> Ask for user input and print out the result or error message  </code>
                    stack.append(temp_result)


<code>def main():</code>
                else:


<code>    while True:</code>
                    result += temp_result


<code>        try:  </code>
    # Check if there is a remaining element and number at the end of the formula and add them to the result         


<code>            formula = input("Enter a chemical formula: ")</code>
    if element:  


<code>            rmm = calculate_rmm(formula)</code>
        if number:  


<code>            print("The relative molecular mass of {} is {:.3f}".format(formula,rmm))</code>
            value = int(number) * elements[element]  


<code>        except KeyError as e:</code>
        else:  


<code>            print("Unknown element: {}".format(e))</code>
            value = elements[element]  


<code>        except ValueError as e:</code>
        result += value   


<code>            print(e)</code>
    return result


<code>if __name__ == "__main__":</code>
<nowiki>#</nowiki> Ask for user input and print out the result or error message  


<code>    main()</code>
def main():
 
    while True:
 
        try:  
 
            formula = input("Enter a chemical formula: ")
 
            rmm = calculate_rmm(formula)
 
            print("The relative molecular mass of {} is {:.3f}".format(formula,rmm))
 
        except KeyError as e:
 
            print("Unknown element: {}".format(e))
 
        except ValueError as e:
 
            print(e)
 
if __name__ == "__main__":
 
    main()
</pre>

2024年3月30日 (六) 15:50的最新版本

#A dictionary of some common elements and their relative atomic masses

elements = {'H': 1.008, 'He': 4.003, 'Li': 6.941, 'Be': 9.012, 

            'B': 10.81, 'C': 12.01, 'N': 14.01, 'O': 16.00, 

            'F': 19.00, 'Ne': 20.18, 'Na': 22.99, 'Mg': 24.31, 

            'Al': 26.98, 'Si': 28.09, 'P': 30.97, 'S': 32.07, 

            'Cl': 35.45, 'K': 39.10, 'Ar': 39.95, 'Ca': 40.08, 

            'Sc': 44.96, 'Ti': 47.87, 'V': 50.94, 'Cr': 52.00, 

            'Mn': 54.94, 'Fe': 55.85, 'Ni': 58.69, 'Co': 58.93, 

            'Cu': 63.55, 'Zn': 65.38, 'Ga': 69.72, 'Ge': 72.63, 

            'As': 74.92, 'Se': 78.96, 'Br': 79.90, 'Kr': 83.80, 

            'Rb': 85.47, 'Sr': 87.62, 'Y': 88.91, 'Zr': 91.22, 

            'Nb': 92.91, 'Mo': 95.94, 'Tc': 98.00, 'Ru': 101.1, 

            'Rh': 102.9, 'Pd': 106.4, 'Ag': 107.9, 'Cd': 112.4, 

            'In': 114.8, 'Sn': 118.7, 'Sb': 121.8, 'I': 126.9, 

            'Te': 127.6, 'Xe': 131.3, 'Cs': 132.9, 'Ba': 137.3, 

            'La': 138.9, 'Ce': 140.1, 'Pr': 140.9, 'Nd': 144.2, 

            'Pm': 145.0, 'Sm': 150.4, 'Eu': 152.0, 'Gd': 157.3, 

            'Tb': 158.9, 'Dy': 162.5, 'Ho': 164.9, 'Er': 167.3, 

            'Tm': 168.9, 'Yb': 173.0, 'Lu': 175.0, 'Hf': 178.5, 

            'Ta': 180.9, 'W': 183.8, 'Re': 186.2, 'Os': 190.2, 

            'Ir': 192.2, 'Pt': 195.1, 'Au': 197.0, 'Hg': 200.6, 

            'Tl': 204.4, 'Pb': 207.2, 'Bi': 208.9, 'Th': 232.0, 

            'Pa': 231.0, 'U': 238.0, 'Np': 237.0, 'Pu': 244.0, 

            'Am': 243.0, 'Cm': 247.0, 'Bk': 247.0, 'Cf': 251.0, 

            'Es': 252.0, 'Fm': 257.0, 'Md': 258.0, 'No': 259.0, 

            'Lr': 262.0, 'Rf': 267.0, 'Db': 270.0, 'Sg': 271.0, 

            'Bh': 270.0, 'Hs': 277.0, 'Mt': 276.0, 'Ds': 281.0, 

            'Rg': 280.0, 'Cn': 285.0, 'Nh': 284.0, 'Fl': 289.0, 

            'Mc': 288.0, 'Lv': 293.0}

# A function to calculate the relative molecular mass of a chemical formula

def calculate_rmm(formula):

    # Initialize the result to zero

    result = 0

    # Initialize an empty string to store the current element symbol

    element = ""

    # Initialize an empty string to store the current number of atoms

    number = ""

    # Initialize an empty list to store the stack of parentheses

    stack = []

    # Loop through each character in the formula

    for char in formula:

        # If the character is an uppercase letter

        if char.isupper():

            # If there is a previous element symbol

            if element:

                # If there is a previous number of atoms

                if number:

                    # Convert the number to an integer and multiply it by the relative atomic mass of the element

                    value = int(number) * elements[element]

                else:

                    # Otherwise assume the number is one and multiply it by the relative atomic mass of the element

                    value = elements[element]

                # If there is a stack of parentheses 

                if stack: 

                    # Append the value to the stack 

                    stack.append(value) 

                else: 

                    # Otherwise add it to the result 

                    result += value 

                # Reset the number to an empty string 

                number = "" 

            # Set the current element symbol to the character 

            element = char 

        # If the character is a lowercase letter 

        elif char.islower(): 

            # Append it to the current element symbol 

            element += char  

        elif char.isdigit():  

            number += char  

        elif char == "(":

            if element:  

                if number:  

                    value = int(number) * elements[element]  

                else:  

                    value = elements[element]  

                if stack:  

                    stack.append(value)  

                else:  

                    result += value   

                element = ""   

                number = ""   

            stack.append(char)   

        elif char == ")":

            if element:

                if number:

                    value = int(number) * elements[element]

                else:

                    value = elements[element]

                if stack:

                    stack.append(value)

                else:

                    result += value

            element = ""

            number = ""

            # Pop the values from the stack until reaching a left parenthesis

            temp_result = 0

            while stack and stack[-1] != "(":

                temp_result += stack.pop()

            # Pop the left parenthesis from the stack

            if stack and stack[-1] == "(":

                stack.pop()

            # Check if there is a number after the right parenthesis

            i = formula.index(char) + 1

            if i < len(formula) and formula[i].isdigit():

                # Multiply the temporary result by the number and append it to the stack or add it to the result

                temp_result *= int(formula[i])

                if stack:

                    stack.append(temp_result)

                else:

                    result += temp_result

                # Skip the next character as it is already processed

                continue

            else:

                # Otherwise append the temporary result to the stack or add it to the result as it is

                if stack:

                    stack.append(temp_result)

                else:

                    result += temp_result

    # Check if there is a remaining element and number at the end of the formula and add them to the result        

    if element:  

        if number:  

            value = int(number) * elements[element]  

        else:  

            value = elements[element]  

        result += value   

    return result

# Ask for user input and print out the result or error message  

def main():

    while True:

        try:  

            formula = input("Enter a chemical formula: ")

            rmm = calculate_rmm(formula)

            print("The relative molecular mass of {} is {:.3f}".format(formula,rmm))

        except KeyError as e:

            print("Unknown element: {}".format(e))

        except ValueError as e:

            print(e)

if __name__ == "__main__":

    main()