在循环内的字典中使用布尔值:第二次向前迭代不给出任何值

Using booleans in dictionary within loop: Second iteration forward gives no values

这里是编程新手。

在 python 中,我正在构建一个允许输入缓冲液 pH 值和氨基酸的三字母代码的脚本。输出应该告诉你它应该与之发生静电相互作用的其他氨基酸。第一次迭代似乎有效,但之后无论输入什么参数,它都停止返回任何输出。我的猜测是以某种方式替换了布尔值或其他东西。有没有办法让每次迭代都重新开始?我希望用户能够继续输入参数并且输出完全不受上一次迭代的影响。

代码如下(如有混乱请见谅):

aaDic = {
         'Arg': 12.48,
         'Asp': 3.90,
         'Cys': 8.37,
         'Glu': 4.07,
         'His': 6.04,
         'Lys': 10.54,
         'Tyr': 10.46,
         }

while True:

    x = input("Enter pH of buffer: ")
    y = input("Enter three letter code for an amino acid: ")


    if float(x) > float(aaDic[y]):
        ProtonationInput = True
    elif float(x) < float(aaDic[y]):
        ProtonationInput = False
    print("\n")
    print("Is your amino acid,", y, ", protonated?", ProtonationInput, "\n")

    print("At pH", x, y, "likely interacts with the following residues: \n")

    for aa in aaDic.keys():
        if float(x) > float(aaDic[aa]):
          aaDic[aa] = True
        elif float(x) < float(aaDic[aa]):
          aaDic[aa] = False
        #print(aa, aaDic[aa], "\n")


    for aa in aaDic.keys():
      if ProtonationInput == True:
            if aaDic[aa] == False:
              print(aa, "\n")
      elif ProtonationInput == False:
            if aaDic[aa] == True:
              print(aa, "\n")

    continue

提前致谢!

您的问题是您正在使用 aaDic 字典来存储浮点值。然后用布尔值覆盖这些值。如下所示,

for aa in aaDic.keys():
        if float(x) > float(aaDic[aa]):
          aaDic[aa] = True
        elif float(x) < float(aaDic[aa]):
          aaDic[aa] = False
        #print(aa, aaDic[aa], "\n")

您的代码依赖于浮点数和布尔值的字典。但是您只使用一本字典。因此,为布尔值制作另一本字典。下面的示例,

aaDic = {
         'Arg': 12.48,
         'Asp': 3.90,
         'Cys': 8.37,
         'Glu': 4.07,
         'His': 6.04,
         'Lys': 10.54,
         'Tyr': 10.46,
         }
# Add this new dictionary of booleans
boolAADic = {key:False for key in aaDic }

while True:

    x = input("Enter pH of buffer: ")
    y = input("Enter three letter code for an amino acid: ")


    if float(x) > float(aaDic[y]):
        ProtonationInput = True
    elif float(x) < float(aaDic[y]):
        ProtonationInput = False
    print("\n")
    print("Is your amino acid,", y, ", protonated?", ProtonationInput, "\n")

    print("At pH", x, y, "likely interacts with the following residues: \n")

    print(aaDic)
    for aa in aaDic.keys():
        if float(x) > float(aaDic[aa]):
          boolAADic[aa] = True # Change to boolean dictionary
        elif float(x) < float(aaDic[aa]):
          boolAADic[aa] = False # Change to boolean dictionary
        #print(aa, aaDic[aa], "\n")


    for aa in aaDic.keys():
      if ProtonationInput == True:
            if boolAADic[aa] == False: # Change to boolean dictionary
              print(aa, "\n")
      elif ProtonationInput == False:
            if boolAADic[aa] == True: # Change to boolean dictionary
              print(aa, "\n")