如何在Python中添加无限多的变量

2024-10-04 11:33:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一点背景:我明年就要上初中了,我想为我在学校要做的事情编写一些方程式会很酷。我已经做了代数方程(在二次方程中解x等等),我认为为化学编写一些代码会很酷。我试图找出如何平衡方程式,我想我可以输入所有的量,使用某个键(比如空格),它会继续到化学方程式的下一部分。这就是我当时的想法

reac1_chem1 = input("Enter the first chemical: ")
reac1_amount1 = input("Enter the amount of " + reac1_chem1 + " atoms: )
reac1_chem2 = input("Enter the second chemical: ")
reac1_amount2 = input("Enter the amount of " + reac1_chem2 + " atoms: )

我想继续这个过程,直到空间作为化学物质进入。我如何使这个过程无限?创建变量是正确的做法还是我应该列出一个清单?如有任何建议,将不胜感激!让我知道这是否在任何方面令人困惑,我可以尝试为您澄清。谢谢


Tags: oftheinput过程amount学校背景enter
2条回答

一本字典就好了:

chemicals = dict()

index = 1
while True:
    chemical = input(f"Enter chemical {index}: ")

    if chemical == " ":
        break
    else:
        chemicals[chemical] = input("Enter the amount: ")
    
    index += 1

print(chemicals)

您可以尝试将信息存储在字典字典中,示例如下:

dct = {"ReactionNameOrID": {"ChemicalName1":"ATOMS", "ChemicalName":"ATOMS2"}}

然后,您可以访问以下信息:

dct.get("ReactionNameOrID").get("ChemicalName1")
#which will return: "ATOMS"

然后,您可以使用一个类来存储其中的所有内容,包括函数

class Reactions():

    #initialize the dictionary
    def __init__(self):
        self.dict_reactions = {}

    #add a function to the class to add more reactions
    def add_chemical(self):
        reaction_name = input("Enter the reaction name/id: ")
        dict_chemicals = input("Enter the chemicals + atoms as dictionary: ")
        self.dict_reactions[reaction_name] = dict_chemicals

MyReactions = Reactions()
# Enter the reaction name/id: FirstReaction
# Enter the reaction name/id: {"H":100, "O":500}
MyReactions.add_chemical()
print(MyReactions.dict_reactions)
#{'FirstReaction': '{"H":100, "O":500}'}

相关问题 更多 >