(创建页面,内容为“<nowiki>#</nowiki> 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, "Ar": 39.95, "K": 39.10 , "Ca" :40.08 ,             'Sc':44.96 , 'T…”)
 
无编辑摘要
第1行: 第1行:
<nowiki>#</nowiki> A dictionary of some common elements and their relative atomic masses
<code><nowiki>#</nowiki> 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, "Ar": 39.95, "K": 39.10 , "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 , 'Co':58.93 , 'Ni':58.69 ,</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.97 , '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.95,'Tc' :98 ,'Ru' :101.07,</code>


            'Rh' :102.91,'Pd' :106.42,'Ag' :107.87,'Cd' :112.41,
<code>            'Rh' :102.91,'Pd' :106.42,'Ag' :107.87,'Cd' :112.41,</code>


            'In' :114.82,'Sn' :118.71,'Sb' :121.76,'Te' :127.60,
<code>            'In' :114.82,'Sn' :118.71,'Sb' :121.76,'Te' :127.60,</code>


            'I':126.90,'Xe':131.29,'Cs':132.91,'Ba':137.33,
<code>            'I':126.90,'Xe':131.29,'Cs':132.91,'Ba':137.33,</code>


            'Hf':178.49,'Ta':180.95,'W':183.84,
<code>            'Hf':178.49,'Ta':180.95,'W':183.84,</code>


            'Ir':192.22,'Pt':195.08,'Au':196.97,
<code>            'Ir':192.22,'Pt':195.08,'Au':196.97,</code>


            'Pb':207.2,'Bi':208.98}
<code>            'Pb':207.2,'Bi':208.98}</code>


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


def calculate_rmm(formula):
<code>def calculate_rmm(formula):</code>


    # Initialize the result to zero
<code>    # Initialize the result to zero</code>


    result = 0
<code>    result = 0</code>


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


    element = ""
<code>    element = ""</code>


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


    number = ""
<code>    number = ""</code>


    # Initialize an empty list to store the stack of parentheses
<code>    # Initialize an empty list to store the stack of parentheses</code>


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


    # Loop through each character in the formula
<code>    # Loop through each character in the formula</code>


    for char in formula:
<code>    for char in formula:</code>


        # If the character is an uppercase letter
<code>        # If the character is an uppercase letter</code>


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


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


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


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


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


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


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


                else:
<code>                else:</code>


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


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


                # If there is a stack of parentheses
<code>                # If there is a stack of parentheses</code>


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


                    # Append the value to the stack
<code>                    # Append the value to the stack</code>


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


                else:
<code>                else:</code>


                    # Otherwise add it to the result
<code>                    # Otherwise add it to the result</code>


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


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


                number = ""
<code>                number = ""</code>


            # Set the current element symbol to the character
<code>            # Set the current element symbol to the character</code>


            element = char
<code>            element = char</code>


        # If the character is a lowercase letter
<code>        # If the character is a lowercase letter</code>


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


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


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


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


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


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


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


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


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


                else:  
<code>                else:  </code>


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


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


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


                else:  
<code>                else:  </code>


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


                element = ""  
<code>                element = ""  </code>


                number = ""  
<code>                number = ""  </code>


            stack.append(char)  
<code>            stack.append(char)  </code>


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


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


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


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


                else:
<code>                else:</code>


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


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


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


                else:
<code>                else:</code>


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


            element = ""
<code>            element = ""</code>


            number = ""
<code>            number = ""</code>


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


            temp_result = 0
<code>            temp_result = 0</code>


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


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


            # Pop the left parenthesis from the stack
<code>            # Pop the left parenthesis from the stack</code>


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


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


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


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


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


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


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


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


                    stack.append(temp_result)
<code>                    stack.append(temp_result)</code>


                else:
<code>                else:</code>


                    result += temp_result
<code>                    result += temp_result</code>


                # Skip the next character as it is already processed
<code>                # Skip the next character as it is already processed</code>


                continue
<code>                continue</code>


            else:
<code>            else:</code>


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


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


                    stack.append(temp_result)
<code>                    stack.append(temp_result)</code>


                else:
<code>                else:</code>


                    result += temp_result
<code>                    result += temp_result</code>


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


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


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


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


        else:  
<code>        else:  </code>


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


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


    return result
<code>    return result</code>


<nowiki>#</nowiki> Ask for user input and print out the result or error message  
<code><nowiki>#</nowiki> Ask for user input and print out the result or error message  </code>


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


    while True:
<code>    while True:</code>


        try:  
<code>        try:  </code>


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


            rmm = calculate_rmm(formula)
<code>            rmm = calculate_rmm(formula)</code>


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


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


            print("Unknown element: {}".format(e))
<code>            print("Unknown element: {}".format(e))</code>


        except ValueError as e:
<code>        except ValueError as e:</code>


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


if __name__ == "__main__":
<code>if __name__ == "__main__":</code>


    main()
<code>    main()</code>

2023年3月11日 (六) 19:51的版本

# 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, "Ar": 39.95, "K": 39.10 , "Ca" :40.08 ,

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

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

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

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

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

            'Nb' :92.91,'Mo' :95.95,'Tc' :98 ,'Ru' :101.07,

            'Rh' :102.91,'Pd' :106.42,'Ag' :107.87,'Cd' :112.41,

            'In' :114.82,'Sn' :118.71,'Sb' :121.76,'Te' :127.60,

            'I':126.90,'Xe':131.29,'Cs':132.91,'Ba':137.33,

            'Hf':178.49,'Ta':180.95,'W':183.84,

            'Ir':192.22,'Pt':195.08,'Au':196.97,

            'Pb':207.2,'Bi':208.98}

# 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()